2015-05-05 16 views
1

我正在使用實體框架和工作單元。如何使用實體框架和工作單元自行更新數據庫級別的列?

我在Person表中有一個小數列OrderBalance,我有一個Order表。我想在db級自己更新orderbalance列以支持併發訂單創建。

我想插入訂單並更新OrderBalance列與atomocity(全部或全部)。

public override void Create(Order order) 
{ 
     _orderReposiory.Add(order); 

     var person = _personRepository.GetById(order.PersonId); 
     person.OrderBalance += order.Amount*order.Price; 

     _personRepository.Edit(person); 

     _unitOfWork.Commit(); 
} 

正如您所看到的,'+ ='進程位於對象級別。我如何在不破壞原子性的情況下在db級別上執行此操作?

回答

1

我用ExeceutSqlCommand與transactionscope,它的工作。

public class PersonRepository : GenericRepository<Person>, IPersonRepository 
    { 
     public void UpdateOrderBalance(decimal amount,long personId) 
     { 
      Entities.Database.ExecuteSqlCommand("Update Person set [email protected] where [email protected]", amount,personId); 
     } 
    } 

我已經改變了我的方法創建這個

public override void Create(Order order) 
     { 
      using (var scope = new System.Transactions.TransactionScope()) 
      { 
       _orderReposiory.Add(order); 
       AddOrderBalancePerson(order); 
       _unitOfWork.Commit(); 
       scope.Complete(); 
      } 
     } 



    private void AddOrderBalancePerson(Order order) 
    { 
     _personRepository.UpdateOrderBalance(order.Amount*order.Price, order.PersonId); 
    } 

EntitiesPersonRepositoryUnitofWork使用相同Dbcontext

0

您需要在兩個存儲庫中使用相同的DbContext實例。如果你這樣做,那麼你可以在交易中包裝任何數量的插入/更新,這將給你全部或全部。 EF報表將自動列入任何待處理的交易。

using (var tran = dbContext.Database.BeginTransaction()) 
{ 
    // your updates here 
}