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.
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();