Linq与实体框架渴望加载

jim*_*jim 2 linq asp.net entity entity-framework nullreferenceexception

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

假设我像这样检索我的ReservationRequest

var c = dataContext.ReservationRequestSet.FirstOrDefault(i => i.id == RequestId);
Run Code Online (Sandbox Code Playgroud)

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

        if (c != null)
        {
            int id = c.Customers.id;
Run Code Online (Sandbox Code Playgroud)

我得到了

    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;
Run Code Online (Sandbox Code Playgroud)

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

谢谢吉姆

Mor*_*avi 5

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

var c = dataContext.ReservationRequestSet.Include("Customers")
                                         .FirstOrDefault(i => i.id == RequestId);
Run Code Online (Sandbox Code Playgroud)

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