执行多个LINQ更新以避免uniquekey异常

时间:2009-09-16 20:15:58

标签: linq transactions batch-file unique-key

我在ParentRef和SortIndex列上有一个带有唯一键的数据库。

在LINQ中,我想切换两个SortIndex值。我想在一个事务中执行此操作,因此可以同时有多个用户。如何使用LINQ一次性切换值,这样我的Unique键不会被违反?

        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();
        }

1 个答案:

答案 0 :(得分: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();
    }