我想要更改具有对象类型的实体类
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);
答案 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);