Domanda

Ho un database con una chiave univoca nelle colonne ParentRef e SortIndex.

In LINQ, voglio cambiare due valori SortIndex. Voglio farlo in una transazione in modo che possano esserci più utenti contemporaneamente. Come posso cambiare i valori con LINQ in una volta sola, quindi la mia chiave unica non viene violata?

        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();
        }
È stato utile?

Soluzione

Penso che per cambiare valori chiave univoci, potrebbe essere necessario utilizzare un terzo valore temporaneo durante lo switch, ovvero:

  • crea nuovo valore
  • imposta page2.SortIndex su un nuovo valore
  • imposta page1.SortIndex sulla vecchia pagina2.SortIndex
  • imposta page2.SortIndex sulla vecchia pagina1.SortIndex

... altrimenti è probabile che si verifichi una violazione della chiave univoca durante il passaggio.

Qualcosa del genere:

    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();
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top