How to seed data with many-to-may relations in Entity Framework Migrations

后端 未结 3 1952
抹茶落季
抹茶落季 2020-12-08 11:35

I use entity framework migration (in Automatic migration mode). Everything is okay, but I have one question:

How should I seed data when I have many-to-many relation

3条回答
  •  有刺的猬
    2020-12-08 11:55

    Ok. I understand how I should be in that situation:

    protected override void Seed(Context context)
    {
        base.Seed(context);
        var buyingItems = new[]
        {
            new BuyingItem
            {
                 Id = 1,
                 Price = 10m
            },
            new BuyingItem
            {
                 Id = 2,
                 Price = 20m,
            }
        }
    
        context.AddOrUpdate(new Parcel() 
        { 
            Id = 1, 
            Description = "Test", 
            Items = new List
            {
                buyingItems[0],
                buyingItems[1]
            }
        },
        new Parcel() 
        { 
            Id = 2, 
            Description = "Test2", 
            Items = new List
            {
                buyingItems[0],
                buyingItems[1]
            }
        });
    
        context.SaveChanges();
    }
    

    There are no duplicates in database.

    Thank you, Ladislav, you gave me a right vector to find a solution for my task.

提交回复
热议问题