如前所述在 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