有没有办法用dbcontext包含所有内容?

时间:2015-02-12 16:38:32

标签: c# asp.net-mvc entity-framework dbcontext eager-loading

在使用预先加载查询DbContext时,需要Include("Navigation")才能填充导航属性。但是在某些情况下,我想简单地Include 实体的所有导航属性。有没有一种方法可以做到这一点,还是一种方法呢?我假设你可以反思,但我宁愿避免这种情况。

我所知道的:

var entity = db.Table.Include("Navigation1").Include("Navigation2").First();

我想要的是什么:

var entity = db.Table.IncludeAll().First(); 

3 个答案:

答案 0 :(得分:4)

没有。那没有。实体框架故意使您明确了解要加载的内容,因为添加联接会使您的查询更重,更慢。这是为了保护你自己。如果你需要联接,那很好,但至少你明确知道你有多少人以及为什么,当你明确指定它们时。

答案 1 :(得分:1)

一个简单的选择是使用反射来检查虚拟属性。

public static IQueryable<T> IncludeAlla<T>(this IQueryable<T> queryable) where T : class
{
    var type = typeof(T);
    var properties = type.GetProperties();
    foreach (var property in properties)
    {
        var isVirtual = property.GetGetMethod().IsVirtual;
        if (isVirtual)
        {
            queryable = queryable.Include(property.Name);
        }
    }
    return queryable;
}

答案 2 :(得分:0)

无论Entity Framework的设计者如何考虑,我都发现存在 一个合法的用例,用于递归地,急切地加载所有数据库项:创建一个数据库内容的快照,该快照很容易通过自动测试恢复。如果您要这样做,您可能会发现this article和这种扩展方法都非常有趣:

public static class EfExtensions
{
    public static IQueryable<TEntity> IncludeAllRecursively<TEntity>(this IQueryable<TEntity> queryable, 
        int maxDepth = int.MaxValue, bool addSeenTypesToIgnoreList = true, HashSet<Type>? ignoreTypes = null)
        where TEntity : class
    {
        var type = typeof(TEntity);
        var includes = new List<string>();
        ignoreTypes ??= new HashSet<Type>();
        GetIncludeTypes(ref includes, prefix: string.Empty, type, ref ignoreTypes, addSeenTypesToIgnoreList, maxDepth);
        foreach (var include in includes)
        {
            queryable = queryable.Include(include);
        }

        return queryable;
    }

    private static void GetIncludeTypes(ref List<string> includes, string prefix, Type type, ref HashSet<Type> ignoreSubTypes, 
        bool addSeenTypesToIgnoreList = true, int maxDepth = int.MaxValue)
    {
        var properties = type.GetProperties();
        foreach (var property in properties)
        {
            var getter = property.GetGetMethod();
            if (getter != null)
            {
                var isVirtual = getter.IsVirtual;
                if (isVirtual)
                {
                    var propPath = (prefix + "." + property.Name).TrimStart('.');
                    if (maxDepth <= propPath.Count(c => c == '.')) { break; }

                    includes.Add(propPath);
                    
                    var subType = property.PropertyType;
                    if (ignoreSubTypes.Contains(subType))
                    {
                        continue;
                    }
                    else if (addSeenTypesToIgnoreList)
                    {
                        // add each type that we have processed to ignore list to prevent recursions
                        ignoreSubTypes.Add(type);
                    }

                    var isEnumerableType = subType.GetInterface(nameof(IEnumerable)) != null;
                    var genericArgs = subType.GetGenericArguments();
                    if (isEnumerableType && genericArgs.Length == 1)
                    {
                        // sub property is collection, use collection type and drill down
                        var subTypeCollection = genericArgs[0];
                        if (subTypeCollection != null)
                        {
                            GetIncludeTypes(ref includes, propPath, subTypeCollection, ref ignoreSubTypes, addSeenTypesToIgnoreList, maxDepth);
                        }
                    }
                    else
                    {
                        // sub property is no collection, drill down directly
                        GetIncludeTypes(ref includes, propPath, subType, ref ignoreSubTypes, addSeenTypesToIgnoreList, maxDepth);
                    }
                }
            }
        }
    }
}

注意:在遍历数据库项时避免循环是必不可少的。默认情况下,它是使用忽略列表ignoreSubTypes完成的:添加了每种可见的类型。这可能并不总是有效(例如,当“字母”项包含类型均为Person的“发件人”和“收件人”时)。在这种情况下,您可以尝试使用maxDepth。祝你好运,但不要自杀!