Entity Framework Core 忽略 .Include(..) 而不间接忽略 .ToList(..)

2023-12-20

如前所述在 EF Core 文档的“加载相关数据”中 https://learn.microsoft.com/en-us/ef/core/querying/related-data我们可以用.Include(..)立即加载导航属性DbSet(或通用IQueryable<T>链接回 EF 上下文)。

这意味着,给定以下模型:

public class TestEntityA
{
    public int Id { get; set; }
    public int TestEntityBId { get; set; }
    public TestEntityB TestEntityB { get; set; }

    public string BProperty { get { return TestEntityB.Property; } }
}

public class TestEntityB
{
    public int Id { get; set; }
    public string Property { get; set; }
}

..那么如下代码应该可以工作:

context.TestEntityAs
    .Include(m => m.TestEntityB)
    .Any(m => m.BProperty == "Hello World");
    /*
     * Note that the below DOES work by using the nav property directly
     * in the query, but that is not always going to be an option for
     * whatever reason. If it's .Included it should be available through
     * INNER JOINing it into the base query before the .Any runs.
     * .Any(m => m.TestEntityB.Property == "Hello World");
     */

然而事实并非如此。

我注意到有一个警告.Include()如果查询不返回最初请求的类型,则可以忽略:

如果更改查询,使其不再返回查询开始时的实体类型的实例,则包含运算符将被忽略。 [snip] 默认情况下,当忽略包含运算符时,EF Core 将记录警告。

我不知道如何在上面的调用中.Any()这是相关的。是的,查询没有返回原始类型(它返回一个bool当然),但同时,警告也不会被记录以表明它被忽略。

我的问题是:

  • 这是一个预期有效的用例吗?我应该在 EF Core 中提出错误吗?
  • 如果没有预料到的话a解决方法如下(调用.ToList())但这显然会加载所有内容,以查明我们是否有任何内容.Any()这很容易成为一个查询(在 EF6 中也是如此)。有什么解决方法可以得到这个.Any()在服务器端工作,因此不需要 ToList 将其放入内存中?

解决方法:

context.TestEntityAs
    .Include(m => m.TestEntityB)
    .ToList()
    .Any(m => m.BProperty == "Hello World");

完整的可重复样本:https://gist.github.com/rudiv/3aa3e1bb65b86ec78ec6f5620ee236ab https://gist.github.com/rudiv/3aa3e1bb65b86ec78ec6f5620ee236ab


通过命名约定,它应该可以工作 您可以尝试使用这段代码来手动配置模型之间的关系

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<TestEntityA>()
        .HasOne(x => x.TestEntityB)
        .WithMany()
        .HasForeignKey(x => x.TestEntityBId);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Entity Framework Core 忽略 .Include(..) 而不间接忽略 .ToList(..) 的相关文章

随机推荐