ADO.NET :: Can Get A Value Or Null From An Entity Query
Mar 28, 2011
Dim p = From i In context.persons
Order By i.fileNum
Select i.ID, i.fileNum, i.firstName, i.lastName, i.state, i.prPenPals.FirstOrDefault.startProfile, i.prPenPals.FirstOrDefault.endProfile
where for every person, prPenPal can have exactly one or zero records? I can do the above, but when I try to use p as the datasource of a ListView I get The cast to value type 'DateTime' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
I tried using
Select i.inmateID, i.fileNum, i.firstName, i.lastName, i.state, i.prLegals.FirstOrDefault.startProfile.ToString,
i.prLegals.FirstOrDefault.endProfile.ToString
but that didn't work. I got a blue squiggly line "Range variable name cannot match the name of a member of the 'Object' class" error I want the date if the record exists, and Null or Nothing if it dosen't.
View 1 Replies
Similar Messages:
Jan 21, 2010
I've got a query such as
Dim MediaQuery =
From m
In dB.DOWNLOADS _Where m.ID = id _Select
which returns a record from the database. One of the fields in the record is a FK to another table. I need to read this value to be able to set a dropdown based on the ID but I can't work out how to access it. For a standard record I can just do the following txtTitle.Text = MediaQuery.FirstOrDefault().TITLE
However with the foreign key it doesn't work like that. I've tried drpGroup.SelectedIndex = MediaQuery.FirstOrDefault().DOWNLOAD_GROUPS.ID where DOWNLOAD_GROUPS is the FK field but it returns Object reference not set to an instance of an object. If you're simply wanting to read some values from a single db record in the entitiy framework and one is a foreign key how should I go about getting the value?
View 2 Replies
Jan 22, 2011
I have a web app for our golf club. When I compute handicap index for each golfer, I have to select the most recent scores and then a subset of those scores depending on how many rounds of golf the golfer has played. All the scores are entered into a single SQL Express table called "Rounds". Verbally, this is what I'm trying to do:
1) select the twenty most recent golf scores (sort on date descending, "take(20)") [if less than 20 records, then select all available];
2) for this set of records, select the 10 lowest scores (or smaller number if golfer has less than 20 rounds);
3) compute the average round differential for the subset of records, etc. to calculate handicap index (this step is working ok...)
My current VB code has this LINQ query (which is flawed -- it selects the lowest handicap differential scores of ALL records for the filtered user):
[Code]....
How do I modify this query to accomplish items 1) & 2) above? It seems this should be simple, but my experience with queries is still limited.
View 2 Replies
Sep 18, 2010
[Code]....
If this information does not exist in the table displays this error:Value Can not BE null. Parameter name: Entity
View 3 Replies
Jul 7, 2010
I'm working on a portal, and I need to check users conection on the ldap.
And if users are members of a special group then it works.
I've exactly used this link to make it works : http://msdn.microsoft.com/en-us/library/ff649227.aspx (almost work)
My point is : my ldap path seems good, no error anymore, when I log with my username and password.But when I querry it, it returns null, but I'm sure my user is in the group :
// Bind to the native AdsObject to force authentication. Object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + username + ")"; search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne(); if(null == result) { return false; }
I'm a normal user, i test with my account. I'm a member of the group that I'm looking for.
View 8 Replies
Jan 21, 2010
here is my code for selectiong some records from db table
string strSql = "select * from mtblNBD where SentTo=@SentTo and InternalStatus Is NULL order by DeadLine desc";
SqlCommand com = new SqlCommand(strSql, con);
com.Parameters.Add("@SentTo", SqlDbType.NVarChar, 50).Value = (string)Session["uname"];
here I am using parameters for SenTo field but not for NULL so it is ok... or should I use parameters for this field where value is NULL , if yes then how can I use parameter for this
View 8 Replies
Jan 21, 2010
When I run the code below, it works
int charId = int.Parse(Request.Params["charId"]);
EveFPT ctx = new EveFPT();
var theCharQuery = from a in ctx.tblChars
where a.id == charId
select new
{
Name = a.name,
CorpName = a.tblCorps.name,
AllianceName = a.tblCorps.tblAlliances.name
};
if(theCharQuery.Count() == 1)
{
var theChar = theCharQuery.First();
lblCharName.Text = theChar.Name;
lblCorpName.Text = theChar.CorpName;
lblAllianceName.Text = theChar.AllianceName;
}
However, If I the below
var theCharQuery = from a in ctx.tblChars
where a.id == charId
select a;
if(theCharQuery.Count() == 1)
{
tblChars theChar = theCharQuery.First();
lblCharName.Text = theChar.name;
lblCorpName.Text = theChar.tblCorps.name;
lblAllianceName.Text = theChar.tblCorps.tblAlliances.name;
}
the statement theChar.tblCorps always returns null.
View 2 Replies
Feb 12, 2010
Tables: Article, Author, Comment (1 article and 1 author can have * comments)In the database is 1 article, 1 author and 1 comment.
The problem is, that code
myBD my_bd = new myBD();
var articles = by_bd.Article;
works OK, I can see that an Author and an Article has 1 comment. But that code
var comm = (from u in my_bd.Comment
where ......
select u);
returns the comment but it has NULL values in property Article and Author. Why ?
View 2 Replies
Feb 24, 2010
I'm using the linq to entity command to perform a record update. I want to set one of the fields back to NULL but I'm not sure how do it. I have a query such as
Dim record = From r in db.LISTS where r.ID = refID Select r
record.Title = txtTitle.text
if txtDetail.text = "" then
record.Detail =
end if
View 3 Replies
Apr 1, 2011
I have to change the username column in my database to nullable, which means everywhere in my code, I now have to check username.HasValue and change references to username to username.Value. Is there anything I can do to avoid having to change all the references to username to username.Value?
View 1 Replies
Jun 28, 2010
Normally I work in ASP Classic, and am still a bit green on ASP.Net MVC.
I have my model with its fields or entities (might not be the right word hence why not able to find if previously answered, forgive me), and some of these will have null values such as hyperlinks, email address, specific types of phone numbers, etc.
What I want to do is not write certain blocks of HTML within the foreach loop if a field is empty.
In ASP Classic, I would have written an If statement along the lines of:
<% If RS.field <> NULL then %>HTML with <%=RS.field %><% End If %>
<% If RS.field2 <> NULL then %>HTML with <%=RS.field2 %><% End If %>
...
However, I don't know how to achieve the same result in ASP.Net MVC.In one of my current usages, a list of sellers returned for a specific set of search results, it runs through a foreach loop and returns the current HTML (in part):
Website: <a class="url" href="<%= seller.ContactWebsite %>" target="_blank" title="Visit the website for <%= seller.Name %>"><%= seller.ContactWebsite %></a><br />
So, if for example I have a field from the model, say seller.ContactWebsite, and this field was NULL, I would not want it to write this as part of the foreach loop.
View 1 Replies
Jul 12, 2010
Hi guys I need to rewrite the sql query below using Linq to entity. Unfortunately I don't have a lot of experience of using Linq.
With TempTableName AS
(SELECT [ColumnName],
[ColumnName2],
[ColumnName3],
[ColumnName4],
ROW_NUMBER() OVER (order by ColumnName desc) as RowNumber from TableName )
SELECT
[ColumnName],
[ColumnName2],
[ColumnName3],
[ColumnName4]
FROM TempTableName WHERE ROWNUMBER
Between 10 and 100
View 1 Replies
Oct 27, 2010
I have the following related tables:
Users
Id
Username
Email
Password
UserStatuses
Id
Name
Users_UserStatus
Id
User (FK - Users: Id)
Status (FK - UserStatuses: Id)
StatusDate
As you can see, UserStatuses is a reference table with various statuses. Users_UserStatus is a join table between Users and UserStatuses. Using Entity Framework, how can I do a conditional to check if the latest StatusDate is "Pending"? As of now, I have the following:
[Code]....
View 1 Replies
Mar 14, 2011
I have a simple Entity query:
[code]....
I then check whether one of the result values is more recent than six months ago using an if..then like so:
If rhcexists.First.SignatureDate > Date.Today.AddMonths(-6) Then
End If
However, if there are no results returned this will return an error. Is there a way for me to tell it to act as if the date is older than six months if there is no value at all? e.g., could I in pseudo do something like:
If Exists(rhcexists.First.SignatureDate, Date.Today.AddMonths(-8)) > Date.Today.AddMonths(-6) Then
End If
View 2 Replies
Jan 26, 2010
Need to figure out the correct way to do a simple SUM function in Linq, but also manipulate one of the feilds coming back by doing a Substring on it, here is the original SQL query:
[Code]....
View 1 Replies
Nov 25, 2010
I am having a meltdown over something that seems so simple and yet isn't working. Here's my scenario.
I have an object structure of tEvents, which contains properties of an event like a run of concerts. tEvents in turn contains an entity set of tEventOptions, which include properties like EventDate, Cancelled etc. I would like to query a list of tEvents using properties of the tEventOptions, for example filtering by date.
My pageis using a calendar object to show event dates. So I am trying to find if any tEvents in the List coming back from the database match the date of the day element being rendered in my Calendar control like so (in this snip 'data' is List and results from a db query):
[code]....
Except r, my query result var, is always true no matter what data it receives. I have tried the sub query using other properties of tEventOption and get the same 'true' result each time. I know that the data does not reflect this result so I clearly have a problem with the structure of my query, but for the life of me I cannot find a way to resolve it.
View 1 Replies
Dec 4, 2010
I have this query for getting data through Entity Framework, which works today. Thing is, i want to create the query dynamically, i.e build it up in blocks, but i can't figure out how exactly to do it. I believe if i can somehow save one of the values that i retrieve in the beginning i can do it, but now i retrieve it twice (probably a bit slow as well? Unless the compiler fixes it before quering). Makes sense? Here is the LINQ:
[code]....
I.e based on if various variables have values.
View 1 Replies
Oct 13, 2010
Best way to show the SQL trace of a LINQ query to Entity Framework 3.5? I am using ASP.net and EF 3.5.
Dim dbo As Web.Portal.RBMEntities = New Web.Portal.RBMEntities
Dim Query = From RoleAllocations In dbo.RoleAllocations Where RoleAllocations.user_id = _ID And RoleAllocations.expire_date > Today Select RoleAllocations
Console write the SQL trace?
View 2 Replies
Nov 6, 2010
I can't seem to figure out how to write this query properly. I've tried various combinations but nothing's worked yet. Below is the relevant portion of my database model: I need to select the products that match a given Category and Group, and that match a given Year, Make, Model, submodel. This I've done below:
ItemList = From P In gDataContext.Products.Include("Groups").Include("Groups.Category1").Include("LookupYearMakeModels") From G In P.Groups Where G.Category = Cat And G.Grp = Group From Y In P.LookupYearMakeModels Where Y.Year = YMM.Year And Y.Make = YMM.Make And Y.Model = YMM.Model And Y.Submodel = YMM.Submodel Select P
I now also have to select products that match the Category, and Group but are Universal (Product.Univeral = True). I'm currently writing two queries, the one above and the one below. I'm merging the results of the two by simply using ItemList.AddRange(ItemList2) ItemList2 = From P In gDataContext.Products.Include("Groups").Include("Groups.Category1") where P.Universal From G In P.Groups Where G.Category = Cat And G.Grp = Group Select P But I want to combine both queries into one and avoid merging the results. How can I do it?
View 2 Replies
Jun 8, 2010
I am very new to entity, sql, c#, and asp.net so this might be something easily fixed. I am attempting to display all the inactive products stored in my table called products in a datagrid.
var productQuery = from b in solutionContext.Version
where b.Product.Name == search && b.Product.ActiveNumber > b.VersionNumber
select new Product
{
Name = b.Product.Name,
Description = b.Product.Description,
ID = b.ID,
LastNumber = b.Product.LastNumber,
MiddleNumber = b.Product.MiddleNumber,
RSTATE = b.RSTATE,
ActiveNumber = b.Product.ActiveNumber,
LastModified = b.Product.LastModified,
ParentID = b.Product.ParentID,
ProductType = b.Product.ProductType
};
ProductsGrid.DataSource = productQuery;
ProductsGrid.DataBind();
I am getting this error: $exception {"The entity or complex type 'SolutionsModel.Product' cannot be constructed in a LINQ to Entities query."} System.Exception {System.NotSupportedException}
View 1 Replies
Nov 29, 2010
I have a strange error, I've tried to search for it before writing this post but I wasn't able to find out a solution yet.
I'm executing a query using ExecuteStoreQuery against a MySQL database, but it throws an exception reporting that there's a syntax error in my SQL.
I've tried to copy&paste the sql query into the MySQL tool and it works nicely, giving the correct results.
I've tried to open manually the connection and using CreateCommand to use it the "old way".
My query is a bit long, 4000 chars more or less, could it be the problem?
View 4 Replies
Jul 30, 2010
I've been working on building a back end on an access database that allows users to search records using a web search box. I've been able to successfully set up simple search query's but have run into trouble where multiple criteria with "AND" statements (OR statements would return too much to be useful). My problem is this, when all five text boxes are filled out the query returns records no problem, but if even one is left blank i get nothing what so ever. Is there any thing I can do in either SQL or VB to either ignore null values entirely or convert them to wildcard values?
View 9 Replies
Jan 3, 2011
I have the following classes:
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
}
public partial class CategoryMap : EntityTypeConfiguration<Category>
{
public CategoryMap()
{
this.HasKey(c => c.CategoryId);
this.Property(c => c.Name).IsRequired().HasMaxLength(400);
}
}
public class MyObjectContext : DbContext
{
public MyObjectContext(string connectionStringName)
: base(connectionStringName)
{
}
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CategoryMap());
base.OnModelCreating(modelBuilder);
}
}
Now when I run the following code I get an exception (GenericArguments[0], 'System.Int32', on 'System.Data.Entity.Internal.Linq.ReplacementDbQueryWrapper`1[TEntity]' violates the constraint of type 'TEntity')
DbDatabase.SetInitializer<MyObjectContext>(new DropCreateDatabaseIfModelChanges<MyObjectContext>());
using (var context = new MyObjectContext("NopSqlConnection"))
{
var query1 = from c in context.Categories
select c.CategoryId;
var test1 = query1.ToList(); //works fine
var query2 = from c in context.Categories
where query1.Contains(c.CategoryId)
orderby c.Name descending
select c;
var test2 = query2.ToList(); //throws the exception
}
View 1 Replies
Sep 9, 2010
I am new to this, and I am trying to implement a linq query similar to db.Genres.Include("Albums") command from
mvc music store using my current DB setup. I realize that the tutorial mentions Checlking the "Include foreign key columns in the method" when creating the tables in ADO.NET, but if I am using LINQ to SQL classes, then how can I obtain the same effect. And how do I use
db.Genres.Include("Albums") to simplify my life?
View 2 Replies
Jan 1, 2010
if LINQ to Entity queries the EDMX class or its .CSDL or SSDL XML on its way to getting data from the RDBMS?
View 8 Replies