0

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

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

1 回答 1

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();
    }
于 2009-09-20T09:06:36.937 回答