如何设置动态类型按对象类型

本文关键字:类型 对象 动态 何设置 设置 | 更新日期: 2023-09-27 18:11:04

我想用对象类型改变我的实体类

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

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

通过使用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);

EDIT:更简单的版本是:

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