我有这些简单的实体:
public class Child
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Parent Parent { get; set; }
}
public class Parent
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
我在种子方法中添加数据,如下所示:
var parent = new Parent { Name = "First" };
context.Parents.AddOrUpdate(p => p.Name, parent);
var children = new[]{
new Child { Parent = parent, Name = "Child1" },
new Child { Parent = parent, Name = "Child2" },
};
context.Children.AddOrUpdate(c => c.Name, children);
这按预期工作,我可以多次更新数据库(更新数据库) - 没有重复。但是,如果我像这样添加第三个孩子:
var parent = new Parent { Name = "First" };
context.Parents.AddOrUpdate(p => p.Name, parent);
var children = new[]{
new Child { Parent = parent, Name = "Child1" },
new Child { Parent = parent, Name = "Child2" },
new Child { Parent = parent, Name = "Child3" },
};
context.Children.AddOrUpdate(c => c.Name, children);
并再次调用 update-database插入第二个父级,现在我在数据库中有两个父级。如果我需要第四个孩子并添加它,则将插入第三个父母,依此类推。
我该如何防止这种情况发生?