实体框架迁移种子重复行

时间:2015-01-16 13:14:49

标签: entity-framework ef-migrations

我有两个班级

public class Category
{
  public int Id { get; set; }
  public string Name { get; set; }
}

public class Item
{
  public int Id { get; set; }
  public sting Name { get; set; }
  public Category Category { get; set; }
}

我有EF迁移和以下种子:

var instockCategory = new Category() { Name = "InStock" };
var outofStockCategory = new Category() { Name = "OutOfStock" };

context.Items.AddOrUpdate(
 d => d.Name,
 new Item() { Name = "Item1", Category = instockCategory },
 new Item() { Name = "Item2", Category = outofStockCategory },
 new Item() { Name = "Item3", Category = outofStockCategory }
);

“d => d.Name”行确保根据项目名称,重新设置数据库时不会有重复记录。 但是,第一次执行此操作时,会创建两个类别为id 1和2的类别。但是第二次运行此类别时,会创建3个新类别! 我可以在不手动添加每个类别的情况下修复此问题吗?

1 个答案:

答案 0 :(得分:3)

您也必须使用AddOrUpdate作为类别。

var instockCategory = default(Category);
var outofStockCategory = default(Category);

context.Set<Category>().AddOrUpdate(
    c => c.Name,
    instockCategory = new Category() { Name = "InStock" },
    outofStockCategory = new Category() { Name = "OutOfStock" }
);

context.Items.AddOrUpdate(
    d => d.Name,
    new Item() { Name = "Item1", Category = instockCategory },
    new Item() { Name = "Item2", Category = outofStockCategory },
    new Item() { Name = "Item3", Category = outofStockCategory }
);

不需要在Context类上显式DbSet

public class Context : DbContext
{
    public DbSet<Item> Items { get; set; }
}