【问题标题】:Linq with Entity Framework Eager Loading带有实体框架急切加载的 Linq
【发布时间】:2011-05-03 14:41:13
【问题描述】:

一个客户有多个 ReservationRequest,一个 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 中的某个设置?

谢谢 吉姆

【问题讨论】:

  • 您使用的是哪个版本的实体框架?最新的支持延迟加载,正如您所期望的那样,否则您必须编写一些额外的代码。
  • 有没有简单的检查方法?
  • 我建议您更改“客户”中 ReservationRequestSet“客户”的导航属性。它更红。

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


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    如果您使用的是实体框架 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
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-09
      • 2012-02-07
      • 1970-01-01
      • 2012-09-10
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      相关资源
      最近更新 更多