播种项目考虑以下几点:有关系
现在public class Foo
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Something { get; set; }
public virtual ICollection<Bar> Bars { get; set; }
}
public class Bar
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Something { get; set; }
[ForeignKey("Foo")]
public int FooId { get; set; }
public virtual Foo Foo { get; set; }
}
,在我的背景,我想与相关Bar
s到种子一些Foo
S:
context.Foos.AddOrUpdate(
r => r.Name,
new Foo
{
Name = "Foo 1",
Something = "Blah",
Bars = new List<Bar>
{
new Bar { Name = "Foo 1 Bar 1", Something = "Blah" },
new Bar { Name = "Foo 1 Bar 2", Something = "Blah" },
new Bar { Name = "Foo 1 Bar 3", Something = "Blah" },
}
},
...
如果我运行Update-Database
一切正常你会期望的,并且我为每个Foo
添加了相关的Bar
。现在
,如果我去改变我的种子数据是这样的:
context.Foos.AddOrUpdate(
r => r.Name,
new Foo
{
Name = "Foo 1",
Something = "BlahBlahBlah",
Bars = new List<Bar>
{
new Bar { Name = "Foo 1 Bar 1", Something = "BlahBlahBlah" },
new Bar { Name = "Foo 1 Bar 2", Something = "BlahBlahBlah" },
new Bar { Name = "Foo 1 Bar 3", Something = "BlahBlahBlah" },
}
},
...
,并再次运行Update-Database
,该Foo
s的更新,但所有的Bar
S的仍会有“嗒嗒”为自己的Something
属性。这是有道理的,因为Entity Framework没有合适的方法来知道应该更新哪个Bar
,但有没有解决方法?也许我可以通过其他方式添加Bar
并将它们与Foo
关联?我知道我可以简单地做:
context.Bars.AddOrUpdate(
r = r.Name,
new Bar
{
...
},
...
但考虑到我使用的标识列钥匙,我也没有办法知道哪些Bar
s到添加到Foo
秒。有任何想法吗?