简体   繁体   English

实体框架核心-延迟加载不适用于Getters

[英]Entity Framework Core - Lazy Loading not working for Getters

Let's assume this scenario 让我们假设这种情况

Entity 实体

public virtual List<Address> AddressHistory { get; set; }

public Address Address
{
    get
    {
        if (AddressHistory.Any())
        {
            return AddressHistory.OrderByDescending(x => x.CreationDate).FirstOrDefault();
        }

        return null;
    }
}

When requesting an address based on a condition, like this : 根据条件请求地址时,如下所示:

dbContext.MyEntity.Where(e => e.Address.Street == "some stuff");

I get a null reference exception. 我得到一个空引用异常。

Why ? 为什么呢 Is there a way to make it work ? 有办法使它起作用吗?

EDIT: for those who think Address might be empty, it works when doing that : 编辑:对于那些认为地址可能为空的人,在这样做的时候可以使用:

dbContext.MyEntity.Where(e => e.AddressHistory.OrderByDescending(x => x.CreationDate).FirstOrDefault().Street == "some stuff");

EDIT: To the guy who marked it as duplicate, I don't think you understand the issue here. 编辑:对于将其标记为重复的人,我认为您在这里不明白这个问题。 Please remove the marking. 请删除标记。

So, to sum up : 因此,总结一下:

If I use the getter => null exception, because the children (AdressHistory) is not lazy loaded. 如果我使用getter => null异常,因为子级(AdressHistory)不会被延迟加载。 If I use the code inside the getters directly in the efcore expression, it works. 如果我直接在efcore表达式中的getter中使用代码,则它可以工作。

Which means using a getter doesn't work in EFCore. 这意味着使用吸气剂在EFCore中不起作用。

You are right, it doesn't work. 您说对了,这行不通。 And I don't think it ever will. 而且我认为永远不会。

EF Core currently has problems with client evaluation of navigation properties (both lazy or eager loaded). EF Core当前在客户端对导航属性(延迟或渴望加载)的评估方面存在问题。 This is one of the reasons client evaluation will be removed in the next EF Core major version (3.0). 这是在下一个EF Core主要版本(3.0) 中将删除客户评估的原因之一。 And queries using such expressions will simply throw exceptions similar to EF6. 使用这种表达式的查询将简单地引发类似于EF6的异常。

With all that in mind, don't use such "helper" properties in LINQ to Entities queries. 考虑到所有这些,不要在LINQ to Entities查询中使用这样的“ helper”属性。 I know this is good from OOP and reusability view, but LINQ query translation does not play well with encapsulation because it's based on knowledge and needs to see the code (expression) behind everything not part of the model mapping to the database. 从OOP和可重用性的角度来看,我知道这很好,但是LINQ查询转换在封装方面不能很好地发挥作用,因为它是基于知识的,并且需要查看模型映射到数据库的所有内容背后的代码(表达式)。

You already know the working solution, simply use it. 您已经知道有效的解决方案,只需使用它即可。 Or take a look at 3rd party extensions like NeinLinq.EntityFrameworkCore which try to address the reusability problem. 或者看一下第三方扩展,例如NeinLinq.EntityFrameworkCore ,它们试图解决可重用性问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM