我升级了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);
之外,我几乎已经升级了所有代码,但不再支持此功能了
我该如何升级?
P.S。我确实想使用通用代码,而不是使用开关添加相应的对象来纠正ObjectSet
附:如果我使用.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
答案 0 :(得分: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;
}
}
}