4

我升级了一个开始的旧项目,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);  
                }  
    }

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

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

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
4

1 回答 1

10

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

示例:context.Set<User>()等价于context.Userssocontext.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;  
        }
    }
}
于 2013-01-20T17:03:29.003 回答