Entity Framework Core Seeding 3 related entities

60 Views Asked by At

I have 3 entities that are related (Account Groups to Account Categories to Accounts). I am trying to seed the database. The code below works for seeding Account Group and Account Category but I am unsure how to seed the next level which is account.

Database Diagram

    var Revenue = new AccountGroup()
            {
                AccountGroupName = "Revenue",
                AccountCategories = new List<AccountCategory>()
                {
                    new AccountCategory { AccountCategoryName = "Base Business Build" },
                    new AccountCategory { AccountCategoryName = "Contract" },
                    new AccountCategory { AccountCategoryName = "Other" }
                }
            };

            _context.AccountGroups.Add(Revenue);

            _context.AccountCategories.AddRange(Revenue.AccountCategories);

            await _context.SaveChangesAsync();

Examples of accounts in the Base Business Build Category would be: Project work, Vertical Sales.

Any help would be greatly appreciated.

1

There are 1 best solutions below

1
On BEST ANSWER

Something like :

foreach(AccountCategories singleCategories  in Revenue.AccountCategories)
{
    _context.Account.AddRange(singleCategories.Acount)
}

await _context.SaveChangesAsync();