'How to insert data into multiple tables with a foreign key using EF core?
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.
Solution 1:[1]
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();
Solution 2:[2]
Another way you can do this as well. In this example more emphasis is put on the Models.
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 virtual ParentEntity ParentEntity {get; set;}
public string Name {get; set;}
}
And here's the usage
var parentEntity = new ParentEntity
{
Name = "Mom"
};
var childEntity = new ChildEntity
{
ParentEntity = parentEntity,
ParentId = parentEntity.Id,
Name = "Junior"
};
context.Add(childEntity);
context.SaveChanges();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jan Paolo Go |
Solution 2 | tisaconundrum |