Print Page | Close Window

Include() combined with FirstOrDefault()

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2009
Forum Discription: For .NET 3.5
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=1139
Printed Date: 28-Apr-2026 at 4:49am


Topic: Include() combined with FirstOrDefault()
Posted By: ken.nelson
Subject: Include() combined with FirstOrDefault()
Date Posted: 13-Mar-2009 at 8:02am

Hello,

In Microsoft EF, we were able to do something like the following:

// In Microsoft EF, c.Orders.Count == 7
Customer c = em.Customer.Where(i => i.Name.BeginsWith("R")).Include("Orders").FirstOrDefault();
if (c != null)
     Console.WriteLine(c.Orders.Count);
 
And as expected, the first Customer or null would be returned, and if not null the print out of the number of orders would be accurate.  When we try the same in DevForce EF it doesn't appear to work the same.  (I need to note that we're talking straight DevForce EF here, not SL).  The Customer will come back, but the number of orders is always 0, as if the Include() is not being used.
 
// In DevForceEF, c.Orders.Count == 0
Customer c = em.Customer.Where(i => i.Name.BeginsWith("R")).Include("Orders").FirstOrDefault();
if (c != null)
     Console.WriteLine(c.Orders.Count);
 
What does seem to work is either of the following:
 
Customer c = null;
foreach (var item in em.Customer.Where(i => i.Name.BeginsWith("R")).Include("Orders"))
{
     c = item;
     break;
}
if (c != null)
     Console.WriteLine(c.Orders.Count);
 
Or:
 
Customer c = em.Customer.Where(i => i.Name.BeginsWith("R")).Include("Orders").Execute().FirstOrDefault();
if (c != null)
     Console.WriteLine(c.Orders.Count);
 
However, if we change the FirstOrDefault() to FirstOrNullEntity(), the "Execute()" solution will fail to compile.
 
Is this working as expected or are we doing something wrong?
 
Thanks,
Ken
 



Replies:
Posted By: smi-mark
Date Posted: 13-Mar-2009 at 11:47am
Hi,

Have you tried doing this?

em.Customer.Where(i => i.Name.BeginsWith("R")).Include("Orders").ToList().FirstOrDefault();


Posted By: kimj
Date Posted: 13-Mar-2009 at 4:46pm
This is actually a known bug which we'd hoped to fix in the 4.3.0 release but did not.  You can use the .Execute() or .ToList() methods as a workaround for now, but more data will be returned than wanted.  Using either of these will submit the full query to EF and the database and then invoke FirstOrDefault() on the results returned to the EM cache. 


Posted By: ken.nelson
Date Posted: 16-Mar-2009 at 8:47am
Ok thanks for the info.



Print Page | Close Window