DbContext上的ObjectContext.AddObject(entityName,entity)的等价物

rad*_*scu 3 c# ado.net entity-framework upgrade entity-framework-5

我升级了一个旧项目,ef4但现在我将其迁移到了ef5.

这是旧代码:

protected void SaveEntity<T>(T entity)
{
        using (DocsManagerContainer context = new DocsManagerContainer())  
                {  
                    string entityType = typeof(T).ToString();  
                    GetLogger().LogMessage("Save " + entityType + " started", LogLevel.Info);  
                    DbTransaction transaction = null;  
                    try  
                    {  
                        context.Connection.Open();  
                        transaction = context.Connection.BeginTransaction();  
                        context.AddObject(typeof(T).Name + "s", entity);  
                        transaction.Commit();  
                        context.SaveChanges();  
                    }  
                    catch (Exception e)  
                    {  
                        GetLogger().LogMessage("Save " + entityType + " thrown error :", e, LogLevel.Error);  
                        throw e;  
                    }  
                    finally  
                    {  
                        context.Connection.Close();  
                        transaction = null;  
                    }  
                    GetLogger().LogMessage("Save " + entityType + " ended", LogLevel.Info);  
                }  
    }
Run Code Online (Sandbox Code Playgroud)

我已经升级了几乎所有的代码,除了:context.AddObject(typeof(T).Name + "s", entity);,但不再支持了.
我怎样升级呢?

ps我确实想使用通用代码,不使用开关来添加相应的对象来纠正ObjectSet ps错误,如果我使用.Set().添加(实体)是:

Error   2   The type 'T' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Entity.DbContext.Set<TEntity>()' D:\work\DocsManager\trunk\DocsManagerDataMapper\EF4Factory\BaseEF4Factory.cs    64  21  DocsManagerDataMapper
Run Code Online (Sandbox Code Playgroud)

Pau*_*ing 9

使用DbContext,您可以使用context.Set<T>().Add(entity);

例如:context.Set<User>()相当于context.Users所以context.Set<User>().Add(myUser)相当于context.Users.Add(myUser).

你想要更接近这个:

protected void SaveEntity<T>(T entity)
    where T : class
{
    using (DocsManagerContainer context = new DocsManagerContainer())  
    {  
        DbTransaction transaction = null;  
        try  
        {  
            context.Connection.Open();  
            transaction = context.Connection.BeginTransaction();  
            context.Set<T>().Add(entity);  
            transaction.Commit();  
            context.SaveChanges();  
        }  
        finally  
        {  
            context.Connection.Close();  
                transaction = null;  
        }
    }
}
Run Code Online (Sandbox Code Playgroud)