5

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.

2 Answers 2

10

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.