Inserting Data
The key methods for adding/inserting entities via the DbContext are Add
and AddRange
.
When an entry is added like this:
var author = new Author{ FirstName = "William", LastName = "Shakespeare" };
context.Add<Author>(author);
context.SaveChanges();
The Author.Id
will automatically be updated with the id generated by the db.
Batch Inserting
We can also add multiple entities at once using AddRange
:
context.Authors.AddRange(
new Author{ FirstName = "William", LastName = "Shakespeare" },
new Author{ FirstName = "Sofia", LastName = "Segovia" },
new Author{ FirstName = "Hugh", LastName = "Howey" },
)
context.SaveChanges();
Performance wise this doesn't change anything from calling Add
multiple times as long as we only call SaveChanges
once at the end. For high performance inserts EFCore.BulkExtensions is currently the way to go.