【问题标题】:Which method is ideal when Seeding a database with Code First Migrations?使用 Code First 迁移为数据库播种时,哪种方法最理想?
【发布时间】:2016-03-23 18:40:53
【问题描述】:

我已经看到了几种使用 AddOrUpdate 方法为数据库播种的不同方法。

1.

    context.People.AddOrUpdate(
      new Person() { Id = 1, Name = "Harry", LastName="Henderson"},
      new Person() { Id= 2, Name = "Henry", LastName="Ford"}
    );

2.

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

有人能解释一下哪种方法更理想/最佳实践吗?为什么你会做一个而不是另一个,或者根本不重要?

【问题讨论】:

  • 您的第一个示例看起来更具可读性,尽管您缺少对重复 ID 的检查。

标签: c# ef-code-first entity-framework-6


【解决方案1】:

种子总是运行。第二个示例将弹出重复键异常。

【讨论】:

  • 我明白这一点,但我要问的是哪种方法是播种数据库的理想/最佳实践方法。
  • 不弹出异常的那个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-31
  • 1970-01-01
  • 2011-08-25
  • 1970-01-01
  • 2012-01-16
  • 1970-01-01
相关资源
最近更新 更多