2015-11-16 25 views
0

我使用EF和Linq處理項目。我加載其分支的DayLock屬性爲False的帳戶(DayLock == false)。有時我會加載一個虛假的daylock值,並且在savechanges daylock值改變之前(它被另一個服務設置爲true)。我希望在天鎖成立時防止任何餘額更新。我該怎麼做?具有SaveChanges上的條件的實體框架

class Program 
{ 
    static void Main(string[] args) 
    { 
     var ctx = new DbTestEntities(); 
     var x = ctx.Accounts.FirstOrDefault(a => a.Id == 1001 && a.Branch.DayLock == false); 
     x.Balance = 3322222222; 

     // After I check this condition (DayLock == false) another process set DayLock = True 
     // I don't want this update (save changes) be commit 

     ctx.SaveChanges(); 

     Console.WriteLine(x.Balance); 
     Console.ReadKey(); 
    } 
} 

另一個進程:

class Program 
{ 
    static void Main(string[] args) 
    { 
     var branch = ctx.Branches.FirstOrDefault(a => a.Id == 2); 
     branch.DayLock = true; 
     ctx.SaveChanges(); 

     Console.ReadKey(); 
    } 
} 

在SQL我可以通過這個查詢做到這一點:

UPDATE [dbo].[Account] 
    SET [Balance] = 100 
WHERE (SELECT [DayLock] FROM [Branch] Where [Id] = [BranchId]) = 1 
+1

這是一個相當複雜的問題,在這裏一個很好的例子http://www.asp.net/mvc/overview/getting-started/getting-started -with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application – DavidG

+0

@DavidG它不能通過行版本或併發解決方案解決 – ArMaN

+0

您可以檢查保存時的原始值。 –

回答

0

你可以嘗試這樣的

using (var dbContextTransaction = entity.Database.BeginTransaction()) 
{ 
    //your code 
    if() // check condition of true or false 
    { 
     //if still false then 
     dbContextTransaction.Commit(); 
    } 
    else 
    { 
     //if turned to true then 
     dbContextTransaction.Rollback(); 
    } 
} 
+0

這只是一個基本的想法 –

0

使用lockEntityEntry

lock (ctx) 
      { 
       if ((bool)ctx.Entry(x).Property("DayLock").CurrentValue == false) 
       { 
        ctx.SaveChanges(); 
       } 
      }