Entity Framework 迁移种子重复行

Entity Framework Migrations seeds duplicate rows

我有两个类

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 个新类别! 我可以在不先手动添加每个类别的情况下解决这个问题吗?

您的类别也必须使用 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 }
);

您的上下文 class 中的显式 DbSet 没有必要。

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