Home > Blockchain >  EF core how to prevent duplicated values for a set of rows
EF core how to prevent duplicated values for a set of rows

Time:07-03

I'm looking for a way to prevent duplicated entries. This is my scenario:

I have a model named Person

    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. 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.

CodePudding user response:

You could add a unique index for your model in the OnModelCreating override on your 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:

[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; }
}

CodePudding user response:

evidence that it worksadd this to the OnModelCreating

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

Please change the property type to string thanks

CodePudding user response:

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();
  • Related