2009-09-16 73 views
0

我有一個ParentRef和SortIndex列上具有唯一鍵的數據庫。執行多個LINQ更新以避免唯一鍵異常

在LINQ中,我想切換兩個SortIndex值。我想在一次交易中這樣做,所以一次可以有多個用戶。我如何使用LINQ一次切換值,所以我的唯一鍵不會被違反?

 var dc = new MyDataContext(); 

     using (TransactionScope trans = new TransactionScope()) 
     { 
      var pageToBeMoved = dc.Pages.Where(p => p.ID == id).Single(); 
      var pageToBeSwitched = (from p in dc.Pages 
            where p.ParentRef == pageToBeMoved.ParentRef 
            where p.SortIndex > pageToBeMoved.SortIndex 
            orderby p.SortIndex ascending 
            select p).First(); 

      int tempSortIndex = pageToBeMoved.SortIndex; 

      pageToBeMoved.SortIndex = pageToBeSwitched.SortIndex; 
      pageToBeSwitched.SortIndex = tempSortIndex; 

      dc.SubmitChanges(); 

      trans.Complete(); 
     } 

回答

0

我認爲要切換唯一鍵值,則可能需要在切換期間使用第三臨時值,即:

  • 創造新的價值
  • 集page2.SortIndex新值
  • 集page1.SortIndex老page2.SortIndex
  • 集page2.SortIndex老page1.SortIndex

......否則,您可能在切換過程中碰到唯一的密鑰違規。

東西沿着這些路線:

var dc = new MyDataContext(); 

    using (TransactionScope trans = new TransactionScope()) 
    { 
     var pageToBeMoved = dc.Pages.Where(p => p.ID == id).Single(); 
     var pageToBeSwitched = (from p in dc.Pages 
           where p.ParentRef == pageToBeMoved.ParentRef 
           where p.SortIndex > pageToBeMoved.SortIndex 
           orderby p.SortIndex ascending 
           select p).First(); 

     int oldMSortIndex = pageToBeMoved.SortIndex; 
     int oldSSortIndex = pageToBeSwitched.SortIndex; 
     // note: here you need to use some value that you know will not already 
     // be in the table ... maybe a max + 1 or something like that 
     int tempSortIndex = someunusedvalue; 

     pageToBeMoved.SortIndex = tempSortIndex; 
     dc.SubmitChanges(); 
     pageToBeSwitched.SortIndex = oldMSortIndex; 
     dc.SubmitChanges(); 
     pageToBeMoved.SortIndex = oldSSortIndex; 
     dc.SubmitChanges(); 
    } 
+0

感謝您的回覆,我已經嘗試設置的第一個0。但是,這並不工作。我正在考慮刪除我的唯一密鑰,並依靠我的代碼與交易一起工作。 – 2009-09-20 19:59:11

+0

它不起作用的方式?你有重大違規行爲嗎? – codeulike 2009-09-20 20:23:19

+0

是的,我願意。正如我的原始代碼一樣。我想這可能與交易有關。 – 2009-09-23 15:28:56