我使用实体框架迁移(在自动迁移模式下)。一切都很好,但我有一个问题:
当我有多对多关系时,我应该如何播种数据?
例如,我有两个模型类:
public class Parcel
{
public int Id { get; set; }
public string Description { get; set; }
public double Weight { get; set; }
public virtual ICollection<BuyingItem> Items { get; set; }
}
public class BuyingItem
{
public int Id { get; set; }
public decimal Price { get; set; }
public virtual ICollection<Parcel> Parcels { get; set; }
}
我了解如何播种简单数据(用于 PaymentSystem 类)和一对多关系,但是我应该在Seed
方法中编写什么代码来生成Parcel
和的一些实例BuyingItem
?我的意思是使用DbContext.AddOrUpdate()
,因为我不想每次运行时都复制数据Update-Database
。
protected override void Seed(ParcelDbContext context)
{
context.AddOrUpdate(ps => ps.Id,
new PaymentSystem { Id = 1, Name = "Visa" },
new PaymentSystem { Id = 2, Name = "PayPal" },
new PaymentSystem { Id = 3, Name = "Cash" });
}
protected override void Seed(Context context)
{
base.Seed(context);
// This will create Parcel, BuyingItems and relations only once
context.AddOrUpdate(new Parcel()
{
Id = 1,
Description = "Test",
Items = new List<BuyingItem>
{
new BuyingItem() { Id = 1, Price = 10M },
new BuyingItem() { Id = 2, Price = 20M }
}
});
context.SaveChanges();
}
此代码创建Parcel
,BuyingItems
以及它们的关系,但如果我BuyingItem
在另一个中需要相同Parcel
(它们具有多对多关系)并且我为第二个包裹重复此代码 - 它将BuyingItems
在数据库中重复(尽管我设置了相同Id
的 s )。
例子:
protected override void Seed(Context context)
{
base.Seed(context);
context.AddOrUpdate(new Parcel()
{
Id = 1,
Description = "Test",
Items = new List<BuyingItem>
{
new BuyingItem() { Id = 1, Price = 10M },
new BuyingItem() { Id = 2, Price = 20M }
}
});
context.AddOrUpdate(new Parcel()
{
Id = 2,
Description = "Test2",
Items = new List<BuyingItem>
{
new BuyingItem() { Id = 1, Price = 10M },
new BuyingItem() { Id = 2, Price = 20M }
}
});
context.SaveChanges();
}
如何BuyingItem
在不同Parcel
的 s 中添加相同的内容?