简体   繁体   English

EF Core - 使用通用方法包含相关实体

[英]EF Core - Include related entities using a generic method

previously, back in EF Frameowrk days, the following method sufficed when needing the related entities to an entity.以前,早在 EF Frameowrk 时代,当需要实体的相关实体时,以下方法就足够了。

private IQueryable<T> EntitySet(params Expression<Func<T, object>>[] includes)
    {
        var set = Context.Set<T>().Where(x => !x.IsDeleted);
        if (includes != null)
        {
            foreach (var include in includes)
            {
                set = set.Include(include);
            }                
        }
        return set;
    }

I'd call this method with something like EntitySet(x => x.People, x => x.People.Meetings) .我会用EntitySet(x => x.People, x => x.People.Meetings)类的东西来调用这个方法。 However, ever since moving to EF core, I can no longer get the related data because I need to explicitly use Include(x.People).ThenInclude(p.Meegings) .但是,自从迁移到 EF 核心后,我无法再获取相关数据,因为我需要显式使用Include(x.People).ThenInclude(p.Meegings)

Is what I'm trying to do even possible in EF core?我在 EF 核心中尝试做的事情是否可行? Or were there so many changes in gather related data so that the above method is no longer applicable?还是在收集相关数据方面发生了太多变化,以至于上述方法不再适用?

It almost seems like you are attempting to add a filter to many queries of the same DbSet.您似乎正试图向同一 DbSet 的许多查询添加过滤器。 Have you looked at Query Filters before in EF Core?您之前在 EF Core 中查看过查询过滤器吗? It seems very similar to what you are trying to do.它似乎与您正在尝试做的事情非常相似。 If you need to have a query should get all records instead of just active records, there is an option to ignore query filters at a by query basis.如果您需要查询应该获取所有记录而不仅仅是活动记录,则可以选择在按查询的基础上忽略查询过滤器。

https://docs.microsoft.com/en-us/ef/core/querying/filters https://docs.microsoft.com/en-us/ef/core/querying/filters

Edit: If you are looking to dynamically specify your includes still.编辑:如果您希望动态指定您的包含仍然。 You can do so with Strings in EF Core the same as was done in EF.您可以在 EF Core 中使用与在 EF 中相同的字符串来执行此操作。 However, the ability to use a lambda to access child objects may have gotten lost in conversion.但是,使用 lambda 访问子对象的能力可能会在转换中丢失。 https://entityframeworkcore.com/knowledge-base/38083198/add-include-expressions-dynamically https://entityframeworkcore.com/knowledge-base/38083198/add-include-expressions-dynamically

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

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