[英]DBContext conversion from ObjectContext
我在EntityFramework 4.0(ObjectContext)中使用此函數。 現在我正在使用EF 5.0。 我的問題是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);
}
如何轉換這個功能?
或者如何制作這樣的功能?
DbContext
是ObjectContext
的適配器(包裝器)。 它還實現了顯式接口IObjectContextAdapter
。 將dbContext轉換為此接口類型,並且包含的ObjectContext
實例將可用:
ObjectContext context = ((IObjectContextAdapter)dbContext).ObjectContext;
BTW新類DbSet<T>
具有方法Find
,它也按鍵搜索實體。 所以,現在你的所有代碼看起來都像
T entity = dbContext.Set<T>().Find(id);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.