문제

Columns 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();
        }
도움이 되었습니까?

해결책

고유 한 키 값을 전환하려면 스위치 중에 세 번째 임시 값을 사용해야 할 수도 있습니다.

  • 새로운 가치를 만듭니다
  • 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();
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top