【发布时间】:2023-04-09 13:39:02
【问题描述】:
我使用实体框架迁移(在自动迁移模式下)。一切都很好,但我有一个问题:
当我有多对多关系时,我应该如何播种数据?
例如,我有两个模型类:
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 及其关系,但如果我在另一个Parcel 中需要相同的BuyingItem(它们具有多对多关系),我将重复此代码第二次parcel - 它将在数据库中复制BuyingItems(尽管我设置了相同的Ids)。
例子:
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();
}
如何在不同的Parcels 中添加相同的BuyingItem?
【问题讨论】:
标签: entity-framework ef-code-first entity-framework-migrations