簡體   English   中英

使用帶有ORM(EF6)的自定義UOW的並行事務問題

[英]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不支持並行事務。”

  1. 我在代碼中做錯了嗎?
  2. UOW中的事務有一些問題?
  3. 不支持將UOW事務與ORM結合使用?
  4. 如果不支持事務,那么當DbContext或任何其他ORM默認實現unitofwork模式時,UnityOfWork模式的目的是什么?

非常感謝您的建議和意見。

[更新]我已通過使上下文接受已經存在的當前交易來解決此問題。 我的解決方法是在代碼CommitTransaction()中。我需要您的注釋。

由此。

  public void CommitTransaction()
  {
   context.SaveChanges();
    transaction.Commit();
    ReleaseCurrentTransaction();
  }

對此。

 public void CommitTransaction()
  {
    context.UseTransaction(this.transaction);
    context.SaveChanges();
    transaction.Commit();
    ReleaseCurrentTransaction();
  }

這種方法有什么缺點嗎? 請分享您的評論。

  1. DbContext不是線程安全的-不要在線程之間使用dbcontext。
  2. 連接字符串應確保連接允許MARS。 見下文。
  3. UoW模式是ORM的最佳實踐。 由EF支持。
  4. EF框架為您管理交易。 無需在基​​本的存儲庫類中添加事務處理。
    添加對象1,更改對象2,刪除對象3,
    然后SaveChanges。
    將由EF作為交易執行。 沒有臟的未提交的讀取。 如果更新之一失敗,則更改將回滾。
  5. 通過消息隊列進行交易。 用於消息隊列的EF和事務范圍有關何時可能要在EF 中使用事務的一般信息有關使用事務的注意事項以及在EF中的操作方法

  6. 盡快處置上下文實例。 一般建議定期更新

連接字符串:請參見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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM