[英]DBContext conversion from ObjectContext
I'm use this function in EntityFramework 4.0 (ObjectContext). 我在EntityFramework 4.0(ObjectContext)中使用此函数。 Now i'm using EF 5.0. 现在我正在使用EF 5.0。 My problem is DefaultContainerName
, GetObjectByKey
methods not found in DBContext
我的问题是DefaultContainerName
,在DBContext
找不到GetObjectByKey
方法
public static T GetObjectByID<T>(int ID, string tableName = "")
{
var localDB = new LocalBaseEntities();
string entitySetName = string.Format("{0}.{1}", localDB.DefaultContainerName, string.IsNullOrEmpty(tableName) ? typeof(T).Name + "s" : tableName);
try
{
IEnumerable<KeyValuePair<string, object>> entityKeyValues =
new KeyValuePair<string, object>[] { new KeyValuePair<string, object>(typeof(T).Name + "ID", ID) };
EntityKey key = new System.Data.EntityKey(entitySetName, entityKeyValues);
return (T)localDB.GetObjectByKey(key);
}
catch (Exception)
{ }
return default(T);
}
How to convert this function? 如何转换这个功能?
Or how to make function like this? 或者如何制作这样的功能?
DbContext
is an adapter (wrapper) over ObjectContext
. DbContext
是ObjectContext
的适配器(包装器)。 Also it implements explicitly interface IObjectContextAdapter
. 它还实现了显式接口IObjectContextAdapter
。 Cast you dbContext to this interface type and wrapped ObjectContext
instance will be available: 将dbContext转换为此接口类型,并且包含的ObjectContext
实例将可用:
ObjectContext context = ((IObjectContextAdapter)dbContext).ObjectContext;
BTW new class DbSet<T>
has method Find
which also searches entities by key. BTW新类DbSet<T>
具有方法Find
,它也按键搜索实体。 So, it seems all your code now will look like 所以,现在你的所有代码看起来都像
T entity = dbContext.Set<T>().Find(id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.