如何避免首先在 EF 代码中插入基于多个字段的重复条目

How to avoid to Insert duplicate entries based on multiple fields in EF code first

假设我有这样一个实体

public class Example
{
    [Key]
    public int ExampleId { get; set; }
    public string Field1 { get; set; }
    public string Field2 { get; set; }
    public string OtherField1 { get; set; }
    public string OtherField2 { get; set; }
}

我需要先使用 EF 代码来创建 table。

我需要防止添加Field1和Field2重复的记录,OtherField1和OtherField2重复没有问题。那些只有 Field1 而不是 Field1 和 Field2 的记录也没有问题。

当然我可以检查所有其他记录是否重复,但正确的方法是强制数据库生成错误。

感谢大家。

插入前检查是否重复(假设 MyExample 是您要插入的新记录):

if(!context.Examples.Any(x => x.Field1 == MyExample.Field1 && x.Field2 == MyExample.Field2)
      context.Examples.Add(MyExample);
      context.SaveChanges();

这就是我们如何使用 EF

在列组合上创建唯一键
[Index("IX_UniqueFields", 1, IsUnique = true)]
public int Field1 { get; set; }

[Index("IX_UniqueFields", 2, IsUnique = true)]
public int Field2 { get; set; }