Entity Framework Code First AddOrUpdate method insert Duplicate values

Ok I was banging my face off the keyboard for an hour with this. If your table’s Id field is an Identity field then it won’t work so use a different one for identifierExpression. I used the Name property and also removed the Id field from the new Hall {...} initializer.

This tweak to the OPs code worked for me so I hope it helps someone:

protected override void Seed(HallContext context)
{
    context.Halls.AddOrUpdate(
        h => h.Name,   // Use Name (or some other unique field) instead of Id
        new Hall
        {
            Name = "Hall 1"
        },
        new Hall
        {
            Name = "Hall 2"
        });

    context.SaveChanges();
}

Leave a Comment