Entity Framework Code First AddOrUpdate method insert Duplicate values

后端 未结 13 1223
清酒与你
清酒与你 2020-12-01 08:52

I have simple entity:

public class Hall
{
    [Key]
    public int Id {get; set;}

    public string Name [get; set;}
}

Then in the S

13条回答
  •  长情又很酷
    2020-12-01 09:35

    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();
    }
    

提交回复
热议问题