entity-framework - Entity Framework 急切加载/"IncludeEverything()"?

标签 entity-framework iqueryable

在 EF4 中,我有一个很小的对象映射,数据量也很小。因此,对于查询,我想立即加载所有关联的数据。是否有任何单个方法调用可以完成这项工作,例如 "IQueryable.IncludeEverything()",而不是使用硬编码的属性名称重复调用 Include()

最佳答案

没有任何开箱即用的东西,但您可以使用 MetadataWorkspace 来实现它:

    public static IQueryable<T> IncludeEverything<T>(this IQueryable<T> query, ObjectContext context)
        where T : class
    {
        var ospaceEntityType = context.MetadataWorkspace.GetItem<EntityType>(
            typeof(T).FullName, DataSpace.OSpace);

        var cspaceEntityType = context.MetadataWorkspace.GetEdmSpaceType(ospaceEntityType);

        var includedTypes = new HashSet<EdmType>();
        includedTypes.Add(cspaceEntityType);

        return IncludeEverything(query, cspaceEntityType as EntityType, "", includedTypes);
    }

    private static IQueryable<T> IncludeEverything<T>(IQueryable<T> query,
        EntityType entity,
        string path,
        HashSet<EdmType> includedTypes)
        where T : class
    {
        foreach (var navigationProperty in entity.NavigationProperties)
        {
            var propertyEdmType = navigationProperty.TypeUsage.EdmType;
            if (includedTypes.Contains(propertyEdmType))
            {
                continue;
            }
            includedTypes.Add(propertyEdmType);

            var propertyCollectionType = propertyEdmType as CollectionType;

            EntityType propertyEntityType;
            if (propertyCollectionType != null)
            {
                propertyEntityType = propertyCollectionType.TypeUsage.EdmType as EntityType;
            } else
            {
                propertyEntityType = propertyEdmType as EntityType;
            }

            var propertyPath = string.IsNullOrEmpty(path) ? "" : path + ".";
            propertyPath += navigationProperty.Name;
            query = query.Include(propertyPath);
            query = IncludeEverything(query, propertyEntityType, propertyPath, includedTypes);
        }

        return query;
    }

请注意,此代码仅用于说明。它没有参数验证,它可能多次包含相同的实体,并且如果模型中有循环,它不会包含所有相关实体。

关于entity-framework - Entity Framework 急切加载/"IncludeEverything()"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12486741/

相关文章:

entity-framework - 在静态类库中放置数据库上下文的利弊

c# - ASP.NET MVC 下拉列表未选择值

c# - Entity Framework 和 VARBINARY

c# - 我如何考虑 IQueryable<className> 的默认数据

c# - 让 IQueryable<int> 集合在 foreach 循环中工作的奇怪问题

c# - Linq 递归搜索

c# - 将 IQueryable 作为参数传递

sql-server-2008 - SQL Server 2008 FILESTREAM 进度指示器

database - 我可以将 Entity Framework 或 Linq To SQL 与 Windows 8 Metro Style 应用程序一起使用吗?

c# - Linq 查询重写