【发布时间】:2016-09-30 15:32:39
【问题描述】:
类似于this question 我在两个字段上有一个唯一索引,将 ID 字段和序列号限制为唯一。现在我通过拖放更改序列号 - 之后这些数字仍然是唯一的。
但 EF(或 SQL Server 分别)拒绝更改,因为它逐记录进行,因此暂时违反了此约束。
是否有任何(EF 内置)机会告诉 SQL Server,在更新几条记录的操作期间,他不必担心约束,但之后?
我不需要任何提示/解决方法,例如在末尾“附加”序列号。
问题是:每当更新唯一索引上的多条记录时,在逐记录操作期间,索引可能会被违反,但之后(在事务结束时)一切都会好起来的。我们如何在 EF 6 中做到这一点?
亲切的问候, 伴侣
代码示例: 1.) 模型和上下文
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.) 片段应用程序
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();
}
}
【问题讨论】:
-
不幸的是,到目前为止,SQL Server 不支持任何类型的deferrable constraints。最好的“解决方法”是编写一个
UPDATE语句,一次性执行所有更改,而不是逐行执行。 SQL 与基于集合的逻辑一起工作很好。
标签: sql-server entity-framework