C# 在为数据库植入代码优先迁移时,哪种方法最理想?

C# 在为数据库植入代码优先迁移时,哪种方法最理想?,c#,ef-code-first,entity-framework-6,C#,Ef Code First,Entity Framework 6,我已经看到了一些使用AddOrUpdate方法对数据库进行种子设定的不同方法 一, 二, var people=新列表{ 新人{Id=1,Name=“Harry”,LastName=“Henderson”}, 新人{Id=2,Name=“Henry”,LastName=“Ford”} }; people.ForEach(newPerson=>context.people.AddOrUpdate(alreadyexistproperty=>alreadyexistproperty.Id,newPe

我已经看到了一些使用AddOrUpdate方法对数据库进行种子设定的不同方法

一,

二,

var people=新列表{
新人{Id=1,Name=“Harry”,LastName=“Henderson”},
新人{Id=2,Name=“Henry”,LastName=“Ford”}
};
people.ForEach(newPerson=>context.people.AddOrUpdate(alreadyexistproperty=>alreadyexistproperty.Id,newPerson));
SaveChanges();

有人能解释一下哪种方法更理想/最佳实践吗。为什么你要一个接一个,或者根本不要紧呢?

种子总是在运行。第二个示例将弹出一个重复密钥异常

您的第一个示例看起来更具可读性,尽管您缺少对重复Id的检查。我理解这一点,但我要问的是,哪种方法是播种数据库的理想/最佳实践方法。一种不会弹出异常的方法。
    context.People.AddOrUpdate(
      new Person() { Id = 1, Name = "Harry", LastName="Henderson"},
      new Person() { Id= 2, Name = "Henry", LastName="Ford"}
    );
    var people = new List<Person>{
    new Person{Id= 1, Name = "Harry", LastName="Henderson"},
    new Person{Id= 2, Name = "Henry", LastName="Ford"}
};
    people.ForEach(newPerson => context.People.AddOrUpdate(alreadyExistsProperty => alreadyExistsProperty.Id, newPerson));
    context.SaveChanges();