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

How Can Set Dynamic Type <T> By Object Type?

我想用对象类型

更改我的实体Class
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);

通过使用 Reflection,您可以通过 x 的 运行 时间类型调用 CreateObjectSet 方法。然后你可以提取键名。这是执行此操作的扩展方法:

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);

编辑: 更简单的版本是:

public static class ObjectContextExtensions
{
    public static EntitySet GetEntitySet<T>(this ObjectContext objectContext, T x)
    {
        return objectContext.CreateObjectSet<T>();
    }
}