Как засеять данные с помощью отношений «многие-к-может» в Entity Framework Migrations

Я использую миграцию структуры сущностей (в режиме автоматической миграции). Все в порядке, но у меня есть один вопрос:

Как мне засеять данные, когда у меня есть отношения «многие ко многим»?

Например, у меня есть два класса моделей:

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?

18
задан Lauren Van Sloun 23 September 2019 в 23:35
поделиться