简体   繁体   中英

DBContext conversion from ObjectContext

I'm use this function in EntityFramework 4.0 (ObjectContext). Now i'm using EF 5.0. My problem is DefaultContainerName , GetObjectByKey methods not found in DBContext

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 . Also it implements explicitly interface IObjectContextAdapter . Cast you dbContext to this interface type and wrapped ObjectContext instance will be available:

ObjectContext context = ((IObjectContextAdapter)dbContext).ObjectContext;

BTW new class DbSet<T> has method Find which also searches entities by key. So, it seems all your code now will look like

T entity = dbContext.Set<T>().Find(id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM