Linq与实体框架渴望加载

时间:2010-11-01 19:30:11

标签: asp.net linq entity-framework entity nullreferenceexception

客户有许多ReservationRequests,ReservationRequest只有一个客户。

假设我像我这样检索ReservationRequest

var c = dataContext.ReservationRequestSet.FirstOrDefault(i => i.id == RequestId);

我得到的ReservationRequest没有问题,但是当我做这样的事情时。

        if (c != null)
        {
            int id = c.Customers.id;

我得到了

    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;

我对EF的经验很少,但是这种类型的东西在nHibernate中没有问题,我错过了EF中的某个设置吗?

由于 吉姆

2 个答案:

答案 0 :(得分:5)

您必须明确地急切加载Customers上的ReservationRequestSet导航属性:

var c = dataContext.ReservationRequestSet.Include("Customers")
                                         .FirstOrDefault(i => i.id == RequestId);

从.NET 4开始,EF默认执行延迟加载,但是由于您正在开发Web应用程序,我建议将其关闭并始终使用Eager Loading,因为它可能希望在对象上下文时尝试进行延迟加载因此,关闭会导致异常,这是Web和WCF应用程序中非常典型的场景。

答案 1 :(得分:1)

如果您正在使用Entity Framework v1,则必须显式加载子项(在检索实体后加载):

if(!c.CustomersReference.IsLoaded)
    c.CustomersReference.Load();

或(在检索实体时急切加载):

var c = dataContext.ReservationRequestSet
                   .Include("Customers")
                   .FirstOrDefault(i => i.id == RequestId);

如果您使用的是Entity Framework v4,则可以尝试使用新的延迟加载功能:

using(YourContext db = new YourContext())
{
    db.ContextOptions.LazyLoadingEnabled = true;
    // query here
}

如果你走这条路,你根本不必担心显式加载导航属性。