2009-09-16 71 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