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.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;  
        }
    }
}
于 2013-01-20T17:03:29.003 に答える