gpt4 book ai didi

c# - 等效于 DbContext 上的 ObjectContext.AddObject(entityName, entity)

转载 作者:行者123 更新时间:2023-11-30 13:47:58 26 4
gpt4 key购买 nike

我升级了一个从 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);,但这不再受支持。
我该如何升级它?

附注我确实想使用通用代码,而不是使用开关添加相应的对象来正确 ObjectSet附:如果我使用 .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

最佳答案

对于 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;
}
}
}

关于c# - 等效于 DbContext 上的 ObjectContext.AddObject(entityName, entity),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14426745/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com