Linq with Entity Framework Eager Loading
A Customer has many ReservationRequests, a ReservationRequest has only one Customer.
Let's say I retrieve my ReservationRequest like so
var c = dataContext.ReservationRequestSet.FirstOrDefault(i => i.id == RequestId);
I get my ReservationRequest without an issue, but when I do something like this.
if (c != null)
{
int id = c.Customers.id;
I get a
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 75: if (c != null)
Line 76: {
Line 77: int id = c.Customers.id;
I have very little experienc开发者_如何学Goe in EF, but this type of thing works in nHibernate without issue, am I missing a setting somewhere in EF?
Thanks Jim
You have to explicitly eager load the Customers
navigation property on ReservationRequestSet
:
var c = dataContext.ReservationRequestSet.Include("Customers")
.FirstOrDefault(i => i.id == RequestId);
As of .NET 4, EF performs lazy loading by default but since you are developing a web application I would suggest to turn it off and always use Eager Loading as it might want to attempt to do lazy loading when your object context is closed, therefore cause an exception which is a very typical scenarios in Web and WCF applications.
If you're using Entity Framework v1, you have to explicitly load children like (to load after you retrieve the Entity):
if(!c.CustomersReference.IsLoaded)
c.CustomersReference.Load();
Or (to eager load when you retrieve the Entity):
var c = dataContext.ReservationRequestSet
.Include("Customers")
.FirstOrDefault(i => i.id == RequestId);
If you're using Entity Framework v4, you could try using the new Lazy-Loading feature:
using(YourContext db = new YourContext())
{
db.ContextOptions.LazyLoadingEnabled = true;
// query here
}
If you go this route, you shouldn't have to worry about explicitly loading navigation properties at all.
精彩评论