How to insert data into multiple tables with a foreign key using EF core?

entity-framework-core

Question

What is the best way to insert data into multiple tables with one or more new rcords containing a foreign key to the first table using Entity Framework Core?

Given these entities:

public class ParentEntity
{
    public int Id {get; set;}
    public string Name {get; set;}
}

public class ChildEntity
{
    public int Id {get; set;}
    public int ParentId {get; set;}
    public string Name {get; set;}
}

I know I can insert the data using this method:

var parentEntity = new ParentEntity {Name = "Mom"};
var childEntity = new ChildEntity {Name = "Junior"};

await db.Parents.AddAsync(parentEntity);
childEntity.ParentId = parentEntity.Id;
await db.Children.AddAsync(childEntity);
await _context.SaveChangesAsync();

But I can see that this will not scale very well. I am learning EF Core right now I cannot find a better way to handle this.

1
1
6/12/2019 4:10:41 PM

Accepted Answer

If you REALLY need to just use foreign key, then that's how you should do it.. it's like doing manual SQL queries.

But EF supports the concept of a navigation property. So you can define your classes like:

public class ParentEntity
{
    public int Id {get; set;}
    public ICollection<ChildEntity> Children { get; } = new List<ChildEntity>();
}

public class ChildEntity
{
    public int Id {get; set;}
    public int ParentId {get; set;}
}

then use it like this

var parentEntity = new ParentEntity();
parentEntity.Children.Add(new ChildEntity());

context.Parents.Add(parentEntity); // parent and its children gets added
context.SaveChanges();
2
6/12/2019 5:04:22 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow