更新唯一索引上的多个序列号

时间:2016-06-01 10:12:14

标签: sql-server entity-framework

类似于this question我在两个字段上有一个唯一索引,将ID字段和序列号限制为唯一。现在我通过拖放更改序列号 - 之后这些数字仍然是唯一的。

但EF(或分别是SQL Server)拒绝更改,因为它按记录进行记录,因此暂时违反此constaint。

是否有任何(EF内置)机会告诉SQL Server他在几个记录的更新操作期间不必担心约束,但之后呢?

我不需要任何tipps /变通办法,例如"追加"序列号最后。

问题是:每当更新唯一索引上的多个记录时,在逐个记录操作期间,索引可能会被违反,但之后(在事务结束时)一切都会好的。我们怎样才能在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();
        }
    }

1 个答案:

答案 0 :(得分:0)

为什么不尝试仅针对给定的交易禁用约束..

我是说, 1)禁用约束 2)更新数据库的值 3)启用约束

如果您需要有关此

的更多信息,请与我们联系 亲爱的伙伴,

我认为我不善于解释,你可以启用/禁用表的特定约束

- 禁用CK_Customer_CustomerType约束 ALTER TABLE Sales.Customer NOCHECK CONSTRAINT CK_Customer_CustomerType

- 做点什么

- 启用CK_Customer_CustomerType约束 ALTER TABLE Sales.Customer CHECK CONSTRAINT CK_Customer_CustomerType

请检查 MSDN Link