如何设置动态类型<t>按对象类型?

时间:2015-09-03 11:25:13

标签: c# entity-framework entity-framework-5

我想要更改具有对象类型的实体类

MyEntity=x.GetType();

ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
ObjectSet<MyEntity> set = objectContext.CreateObjectSet<MyEntity>();
IEnumerable<string> keyNames = set.EntitySet.ElementType
                                            .KeyMembers
                                            .Select(k => k.Name);

更改为

ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
ObjectSet<x.GetType()> set = objectContext.CreateObjectSet<x.GetType()>();
IEnumerable<string> keyNames = set.EntitySet.ElementType
                                            .KeyMembers
                                            .Select(k => k.Name);

1 个答案:

答案 0 :(得分:2)

使用Reflection,您可以按CreateObjectSet的运行时类型调用x方法。然后,您可以提取密钥名称。这是一个执行此操作的扩展方法:

public static class ObjectContextExtensions
{
    public static EntitySet GetEntitySet(this ObjectContext objectContext, object x)
    {
        //Get the approperiate overload of CreateObjectSet method
        var methodInfo = typeof(ObjectContext).GetMethods()
                         .Where(m => m.Name == "CreateObjectSet").First();

        //Supply the generic type of the method
        var genericMethodInfo = methodInfo.MakeGenericMethod(x.GetType());

        //Invoke the method and get the ObjectSet<?> as an object          
        var set = genericMethodInfo.Invoke(objectContext, new object[] { });

        //Retrieve EntitySet of the set
        var prop = set.GetType().GetProperty("EntitySet");
        var entitySet = (EntitySet)prop.GetValue(set);
        return entitySet;
    }
}

现在您可以将代码更新为:

ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
var set = objectContext.GetEntitySet(x);
var keyNames =  set.ElementType.KeyMembers.Select(k => k.Name);