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

后端 未结 3 1959
抹茶落季
抹茶落季 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:50

    You must fill many-to-many relation in the same way as you build many-to-many relation in any EF code:

    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
            {
                new BuyingItem() { Id = 1, Price = 10M },
                new BuyingItem() { Id = 2, Price = 20M }
            }
        });
    
        context.SaveChanges();
    }
    

    Specifying Id which will be used in database is crucial otherwise each Update-Database will create new records.

    AddOrUpdate doesn't support changing relations in any way so you cannot use it to add or remove relations in next migration. If you need it you must manually remove relation by loading Parcel with BuyingItems and calling Remove or Add on navigation collection to break or add new relation.

提交回复
热议问题