[英]Parallel transaction issue using custom UOW with ORM(EF6)
我嘗試將通用存儲庫和UOW模式與Entity Framework一起實現為ORM的一些背景知識。我已經使用方法編寫了自定義UnitOFWork類
1.BeginTransaction。 2.CommitTransaction 3.RollBackTransaction 4.SaveChanges 5.IsInTransaction 6.Dispose。
public class UnitOfWork: IUnitOfWork
{
private DbTransaction transaction;
private readonly DbContext context;
public UnitOfWork(DBContext dbContext )
{
context = dbContext ;
}
public void Begintransaction()
{
transaction = context.Database.Connection.BeginTransaction(isolationLevel);
}
public void CommitTransaction()
{
context.SaveChanges();
transaction.Commit();
ReleaseCurrentTransaction();
}
....
....
}
我的通用存儲庫類
public class Repository : IRepository
{
private dbContext;
protected DBContext Context
{
get
{
return dbContext != null? dbContext : dbContext = GetContextFromFactory();
}
}
public void Add<T>(T entity)
{
dbContext.Set<T>.Add(entity);
}
}
我的個人資料庫。
public class PersonRepository : Repository
{
public void AddPerson(Person person)
{
using(var uow = new UnitOfWork(Context)
{
try
{
uow.BeginTransaction();
Add(person);
uow.CommitTransaction();
}
catch (Exception ex)
{
uow.RollBackTransaction();
log.Error("This Exception:",ex);
}
}
}
}
var repo = new PersonRepository();
Person person = GetPerson();
repo.AddPerson(person);
當我運行此代碼以保存人員對象時,它將在UOW的CommitTransaction()方法中的context.SaveChanges()上引發異常。 例外是“ SqlConnection不支持並行事務。”
非常感謝您的建議和意見。
[更新]我已通過使上下文接受已經存在的當前交易來解決此問題。 我的解決方法是在代碼CommitTransaction()中。我需要您的注釋。
由此。
public void CommitTransaction()
{
context.SaveChanges();
transaction.Commit();
ReleaseCurrentTransaction();
}
對此。
public void CommitTransaction()
{
context.UseTransaction(this.transaction);
context.SaveChanges();
transaction.Commit();
ReleaseCurrentTransaction();
}
這種方法有什么缺點嗎? 請分享您的評論。
通過消息隊列進行交易。 用於消息隊列的EF和事務范圍有關何時可能要在EF 中使用事務的一般信息有關使用事務的注意事項以及在EF中的操作方法
盡快處置上下文實例。 一般建議定期更新
連接字符串:請參見MultipleActiveResultSets = true
<connectionStrings>
<add name="myConn" connectionString="Data Source=localhost;Initial Catalog=MyDbName ;Integrated Security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.