Realice múltiples actualizaciones de LINQ para evitar una excepción de clave única
-
07-07-2019 - |
Pregunta
Tengo una base de datos con una clave única en las columnas ParentRef y SortIndex.
En LINQ, quiero cambiar dos valores de SortIndex. Quiero hacer esto en una transacción para que pueda haber múltiples usuarios a la vez. ¿Cómo, con LINQ, cambio los valores de una vez, para que no se viole mi clave 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();
}
Solución
Creo que para cambiar valores de clave únicos, es posible que deba usar un tercer valor temporal durante el cambio, es decir:
- crear nuevo valor
- establece page2.SortIndex en un nuevo valor
- establece page1.SortIndex en la página antigua2.SortIndex
- establece page2.SortIndex en la página antigua1.SortIndex
... de lo contrario, es probable que encuentre una violación de clave única durante el cambio.
Algo en este sentido:
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();
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow