Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 具有实体框架的Linq_Asp.net_Linq_Entity Framework_Entity_Nullreferenceexception - Fatal编程技术网

Asp.net 具有实体框架的Linq

Asp.net 具有实体框架的Linq,asp.net,linq,entity-framework,entity,nullreferenceexception,Asp.net,Linq,Entity Framework,Entity,Nullreferenceexception,一个客户有多个ReservationRequests,一个ReservationRequest只有一个客户 假设我这样检索我的预订请求 var c = dataContext.ReservationRequestSet.FirstOrDefault(i => i.id == RequestId); 我得到我的预订请求没有问题,但当我做这样的事情时 if (c != null) { int id = c.Customers.id;

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

假设我这样检索我的预订请求

var c = dataContext.ReservationRequestSet.FirstOrDefault(i => i.id == RequestId);
我得到我的预订请求没有问题,但当我做这样的事情时

        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中的某个设置

谢谢
Jim

您必须在
ReservationRequestSet
上显式加载
Customers
导航属性:

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

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

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

或(在检索实体时要立即加载):


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

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

如果您这样做,就不必担心显式加载导航属性。

您使用的是哪个版本的实体框架?最新版本支持延迟加载,正如您所期望的那样,否则您必须编写一些额外的代码。是否有一种简单的检查方法?我建议您更改“Customer”中ReservationRequestSet“Customers”的导航属性。它更可编辑。
var c = dataContext.ReservationRequestSet
                   .Include("Customers")
                   .FirstOrDefault(i => i.id == RequestId);
using(YourContext db = new YourContext())
{
    db.ContextOptions.LazyLoadingEnabled = true;
    // query here
}