问题描述
如 EF 核心文档的加载相关数据"中的 所述 我们可以使用 .Include(..)
从 DbSet
(或通用的 IQueryable
链接回到 EF 上下文).
As noted in "Loading Related Data" from EF Core Documentation we can use .Include(..)
to Eagerly Load navigation properties from the DbSet
(or generic IQueryable<T>
linking back to an EF context).
这意味着,给定以下模型:
This means that, given the following models:
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; }
}
...然后像下面这样的代码应该可以工作:
.. then code such as the following should work:
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()
可以被忽略:
I note that there is a caveat where .Include()
could be ignored should a query not return the type that is initially requested:
如果您更改查询以使其不再返回查询开始的实体类型的实例,则包含运算符将被忽略.[snip] 默认情况下,EF Core 会在忽略包含运算符时记录警告.
我不确定在上面对 .Any()
的调用中是如何相关的.是的,查询没有返回原始类型(当然它返回一个 bool
),但同时,也没有记录警告以表明它被忽略了.
I'm not sure how, in the above call to .Any()
that is relevant. Yes, the query is not returning the original type (it's returning a bool
of course) but at the same time, the Warning is also not logged to advise that it is being ignored.
我的问题是:
- 这是一个预期有效的用例吗?我应该在 EF Core 中提出错误吗?
- 如果不是预期的,a 解决方法如下(调用
.ToList()
),但这显然会加载所有内容,以确定我们是否有任何内容一个.Any()
很容易成为一个查询(在 EF6 中也是如此).让这个.Any()
在服务器端工作从而不需要 ToList 将其放入内存的解决方法是什么?
- Is this a usage case that is expected to work? Should I raise a bug in EF Core?
- If it's not expected, a workaround is as below (to call
.ToList()
) but that would obviously load everything, to find out if we have anything on a.Any()
which could easily be a query (and would be as such in EF6). What is a workaround to get this.Any()
to work on the server side thus not requiring the ToList to put it in memory?
解决方法:
context.TestEntityAs
.Include(m => m.TestEntityB)
.ToList()
.Any(m => m.BProperty == "Hello World");
完全可重复的示例:https://gist.github.com/rudiv/3aa3e1bb65b86ec78ee2f362a/p>
Full reproducible sample: https://gist.github.com/rudiv/3aa3e1bb65b86ec78ec6f5620ee236ab
推荐答案
按命名约定它应该可以工作您可以尝试使用这段代码手动配置模型之间的关系
by naming convention it should be workedyou can try using this piece of code to manual configure relation beetwen your models
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TestEntityA>()
.HasOne(x => x.TestEntityB)
.WithMany()
.HasForeignKey(x => x.TestEntityBId);
}
这篇关于Entity Framework Core 间接忽略 .Include(..) 而没有 .ToList(..)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!