【问题标题】:Get all entities and their navigational properties获取所有实体及其导航属性
【发布时间】:2016-04-14 08:28:29
【问题描述】:

我正在尝试获取所有实体(模型),然后是它们的导航属性,它们的类型仅为 ICollection,但它似乎不起作用。这是我迄今为止尝试过的:

foreach (var propertyInfo in new CompanyDBContext().GetType()
                    .GetProperties(
                            BindingFlags.Public
                            | BindingFlags.Instance))
{
    Console.WriteLine(propertyInfo.Name);

    //var entity = DbSet<propertyInfo.Name>
}

我可以使用上面的代码获取我拥有的所有模型,但是如何获取所有类型为 ICollection next 的导航属性?

【问题讨论】:

标签: c# entity-framework


【解决方案1】:

您必须首先从DbContext 获取所有实体的类型。在DbContext 中定义的任何DbSet&lt;&gt; 类型的属性实际上都包含一个实体。你需要抓住它。

private static readonly Type DbSetType = typeof(DbSet<>);
private static IEnumerable<Type> GetAllEntityTypes(Type contextType)
{
    return contextType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .Select(p => p.PropertyType)
        .Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == DbSetType)
        .Select(t => t.GetGenericArguments()[0]);
}

为了从Entity 类型中获取导航属性,这里有一个辅助方法,它是https://stackoverflow.com/a/27124251/2509344 的修改版本

private static readonly MethodInfo CreateObjectSetMethodInfo = typeof(ObjectContext).GetMethod("CreateObjectSet", new Type[0]);
private static readonly Type CollectionType = typeof(ICollection<>);
private static IEnumerable<PropertyInfo> GetNavigationProperties(DbContext context, Type entityType)
{
    var objectContext = ((IObjectContextAdapter)context).ObjectContext;
    var createObjectSetMethod = CreateObjectSetMethodInfo.MakeGenericMethod(entityType);
    var entity = createObjectSetMethod.Invoke(objectContext, new object[0]);

    var entitySet = (EntitySet)entity.GetType().GetProperty("EntitySet").GetValue(entity);
    var elementType = entitySet.ElementType;
    return elementType.NavigationProperties.Select(p => entityType.GetProperty(p.Name))
        // Filter Properties that are of type ICollection
        .Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == CollectionType);
}

并最终获得在DbContext 中定义的实体的所有导航属性:

var context = new CompanyDBContext();
var entities = GetAllEntityTypes(context.GetType());
foreach (var entity in entities)
{
    var navigationProperties = GetNavigationProperties(context, entity).ToList();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多