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

问题描述 投票:0回答:2

假设我有这样的实体

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代码创建表。

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

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

感谢所有人。

c# database entity-framework ef-code-first
2个回答
0
投票

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

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

0
投票

这是我们可以使用EF在列组合上创建唯一键的方式

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

[Index("IX_UniqueFields", 2, IsUnique = true)]
public int Field2 { get; set; }
© www.soinside.com 2019 - 2024. All rights reserved.