简体   繁体   English

实体框架核心包含(……在哪里)

[英]Entity Framework Core Include(…Where)

According to the docs we have the possibility to use Where() inside Include in EF Core 5. So this code is working well:根据文档,我们可以在 EF Core 5 的Include中使用Where() 。所以这段代码运行良好:

var groups = dbContext.DocumentGroups
                      .Include(e => e.Types.Where(x => true))
                      .OrderBy(e => e.Name);

Now I have to refactor my filter (in this case simplified) - so I tried an extension method like this:现在我必须重构我的过滤器(在这种情况下是简化的) - 所以我尝试了这样的扩展方法:

public static IEnumerable<T> MyFilter<T>(this IEnumerable<T> query)
{
    // ... do a lot of filter stuff here
    return query.Where(e => true);
}

and call it like this:并这样称呼它:

var groups = dbContext.DocumentGroups
                      .Include(e => e.Types.MyFilter())
                      .OrderBy(e => e.Name);

I get an exception:我得到一个例外:

The expression 'e.Types.MyFilter(__dbContext_1)' is invalid inside an 'Include' operation, since it does not represent a property access: 't => t.MyProperty'.表达式“e.Types.MyFilter(__dbContext_1)”在“包含”操作中无效,因为它不代表属性访问:“t => t.MyProperty”。 To target navigations declared on derived types, use casting ('t => ((Derived)t).MyProperty') or the 'as' operator ('t => (t as Derived).MyProperty').要定位在派生类型上声明的导航,请使用强制转换 ('t => ((Derived)t).MyProperty') 或 'as' 运算符 ('t => (t as Derived).MyProperty')。 Collection navigation access can be filtered by composing Where, OrderBy(Descending), ThenBy(Descending), Skip or Take operations.集合导航访问可以通过组合 Where、OrderBy(Descending)、ThenBy(Descending)、Skip 或 Take 操作进行过滤。 For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393 .有关包含相关数据的详细信息,请参阅http://go.microsoft.com/fwlink/?LinkID=746393

How can I fix this?我怎样才能解决这个问题?

I think the main thing here is that you need to provide an Expression to your include.我认为这里的主要内容是您需要为您的包含提供一个Expression If you want to refactor and have it as a testable, reusable independent unit you can create for example a static Expression property that you then can pass to the Include method.如果您想重构并将其作为可测试、可重用的独立单元,您可以创建例如 static 表达式属性,然后您可以将其传递给Include方法。

Something like;就像是;

public static Expression<Func<MyStoreObject, IEnumerable<MySubType>>> MyIncludeExpression 
{
   get { return e => e.Types.Where(x => true); }
}

( MyStoreObject being the type of the DocumentGroups, MySubType being the type of the property Types enumerable.) MyStoreObject是 DocumentGroups 的类型, MySubType是属性Types可枚举的类型。)

and call it with并调用它

var groups = dbContext.DocumentGroups
                .Include(MyClass.MyIncludeExpression)
                .OrderBy(e => e.Name);

See the documentation of the EntityFrameworkQueryableExtensions.Include Method .请参阅EntityFrameworkQueryableExtensions.Include 方法的文档。

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

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