EF Core – ContainsAsync verification is failed. Duplicated registers

Try this

foreach(var element in elements)
{
  

  if ((await context.Itens.FindAsync(element.Id)!=null)
{
var item = new Item
  {
    Id = element.Id,
    ...
  }
    context.Itens.Add(item);
}
}

await context.SaveChangesAsync();

if you don’t need to check Id in DB, just create list of the items and add them there each time checking if it already exist:

var items= List<Item>();

foreach(var element in elements)
{
  

  if (!items.Any(i=>i.Id==elementId))
{

var item = new Item
  {
    Id = element.Id,
    ...
  }
    items.Add(item);
}
}

  context.Items.AddRange(items.ToArray());
await context.SaveChangesAsync();

or if you have millions elements then


var items= List<Item>();

foreach(var element in elements)
{
  
var item = new Item
  {
    Id = element.Id,
    ...
  }
    items.Add(item);
}

var distinctItems = items.Distinct(new DistinctItemComparer());

  context.Items.AddRange(distinctItems.ToArray());
await context.SaveChangesAsync();

class DistinctItemComparer : IEqualityComparer<Item> {

    public bool Equals(Item x, Item y) {
        return x.Id == y.Id;
         // &&  x.Name == y.Name;
     }

    public int GetHashCode(Item obj) {
        return obj.Id.GetHashCode() 
        //  ^  obj.Name.GetHashCode() ^
      }
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top