简体   繁体   English

EF核心如何防止一组行的重复值

[英]EF core how to prevent duplicated values for a set of rows

I'm looking for a way to prevent duplicated entries.我正在寻找一种防止重复条目的方法。 This is my scenario:这是我的场景:

I have a model named Person我有一个名为 Person 的 model

    public class Person 
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public string Citizenship { get; set; }
    }

If I insert the first record with name John, surname Doe and citizenship American.如果我插入第一条名为 John、Doe 和美国公民身份的记录。 Subsequently, if I insert another record as name John, surname Doe and citizenship French, I want EF Core to pick that up as a duplicate because we already have John Doe as an existing record.随后,如果我插入另一条记录,名称为 John、Doe 和法国公民身份,我希望 EF Core 将其作为副本提取,因为我们已经将 John Doe 作为现有记录。

证明它有效的证据 add this to the OnModelCreating将此添加到 OnModelCreating

  modelBuilder.Entity<Person>()
              .HasIndex(e => new { e.Name, e.Surname })
              .IsUnique();

Please change the property type to string thanks请将属性类型更改为字符串谢谢

You could add a unique index for your model in the OnModelCreating override on your DbContext .您可以在 DbContext 的OnModelCreating覆盖中为您的DbContext添加唯一索引。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Person>()
        .HasIndex(p => new { p.Name, p.Surname })
        .IsUnique();
}

Or as an attribute on your Person class:或者作为您的 Person class 的属性:

[Index(nameof(Name), nameof(Surname), IsUnique=true)]
public class Person
{
   public int Id { get; set; }
   public string Name { get; set; }
   public string Surname { get; set; }
   public string Citizenship { get; set; }
}

You can use this extention for this:您可以为此使用此扩展:

public static class LinqExtention
    {
        public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property)
        {
            return items.GroupBy(property).Select(x => x.First());
        }
    }

usage:用法:

var newList= db.persons.DistinctBy(x=>new {x.Name,x.Surname }).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM