similar to this question I have a unique index on two fields, constraining an ID field and the sequence number to be unique. Now I change the sequence numbers via drag and drop - after that these numbers are still unique.
But EF (or the SQL Server respectively) refuse the change since it proceeds record by record, therefore violating this constaint temporarily.
Is there any (EF-built-in) chance to tell SQL Server that he has not to worry about constraints during the update operation of several records, but afterwards?
I do not need any tipps/workarounds like "appending" sequence numbers at the end.
The problem is: Whenever updating multiple records on an unique index, during the record-by-record-operation the index might be violated, but afterwards (at the end of the transaction) everything will be fine. How can we do this in EF 6?
Kind regards, Mate
Code sample: 1.) Model und Context
public class Model
{
[Key]
public long Key { get; set; }
[Index("MyUniqueIndex", IsUnique = true)]
public long IndexField { get; set; }
}
public class ModelContext : DbContext
{
public DbSet<Model> ModelDbSet { get; set; }
public ModelContext()
: base("name = ModelContext")
{
Database.Log = Console.Write;
}
}
2.) Snippet Application
private void button1_Click(object sender, EventArgs e)
{
CreateRecords();
}
private void button2_Click(object sender, EventArgs e)
{
SwapIndexAndSave();
}
public static void CreateRecords()
{
using (ModelContext context = new ModelContext())
{
// Create two records
// Record 1 has value 1 in the unique index field
// Record 2 has value 2 in the unique index field
Model newModel1 = new Model {IndexField = 1};
context.ModelDbSet.Add(newModel1);
Model newModel2 = new Model {IndexField = 2};
context.ModelDbSet.Add(newModel2);
context.SaveChanges();
}
}
public static void SwapIndexAndSave()
{
using (ModelContext context = new ModelContext())
{
// Load both records
List<Model> data = context.ModelDbSet.ToList();
// Swap values in unique index field
// Record 1 will get value 2 in the unique index field
// Record 2 will get value 1 in the unique index field
foreach (Model model in data)
{
model.IndexField = 3 - model.IndexField;
}
// SaveChanges crashes, because on updating the first record will
// result in identically values for the unique index field on the database.
context.SaveChanges();
}
}