C#C
C#4y ago
Kamil Pisz

[EFCore] add many Parent entities with Child entities, How to connect them in single SaveChanges

Hello, im trying to sync data in my database with data in external source
there is a example that i have list of MainCategories (parent) and Categories(child)

!! code screen from IDE for better visibility in comments

var listOfParentCategoriesFromExternalSource;

var newListOfParentCategoryToAdd = new List<ParentCategory>();
foreach(parent in listOfParentCategoriesFromExternalSource)
{
    var newParentCategory = ParentCategory();
    newParentCategory.Name = "Main Category Name";

    var newListChildCategoryToAdd = new List<ChildCategory>();
    foreach(child in parent)
    {
        var newChildCategory = ChildCategory();
        newChildCategory.Name ="Child Category Name"
        newChildCategory.ParentId = ??   // < --------- How to make connection ?

        newListChildCategoryToAdd.Add(newChildCategory)  //----Prepare list to AddRange

    }
    newListOfParentCategoryToAdd.Add(newParentCategory) //----Prepare list to AddRange
}
await _dbContext.ParentsCategory.AddRangeAsync(newListOfParentCategoryToAdd);
await _dbContext.ParentsCategory.AddRangeAsync(newListChildCategoryToAdd);
await _dbContext.SaveChangesAsync();
Was this page helpful?