Is it possible to add list of object to Context in entity framework without using foreach addObject ?
thanks for help
You can use Entity Framework's . AddRange method to add a collection of objects to your Db. List<T> implements IEnumerable MSDN - msdn.microsoft.com/en-us/library/6sh2ey19(v=vs. 110).
You can add multiple records or multiple objects using the AddRange method of DbSet as shown in the following code. The code creates a list of department objects and inserts two new departments to the list. We add the list to the context using the AddRange method.
Insert Data Add method to add a new entity to a context (instance of DbContext ), which will insert a new record in the database when you call the SaveChanges() method. In the above example, context. Students. Add(std) adds a newly created instance of the Student entity to a context with Added EntityState.
From EntityFramework 6 you can use DbSet.AddRange Method (IEnumerable) like this
db.companies.AddRange(newCompanies);
Generally you can't do that - you have to do it in a loop. In some cases, however, you can avoid adding every object - specifically, if you have an entity graph and you add the parent node. E.g. if you have a Company
object that has a collection of Employees
:
context.AddToCompanies(company);
/* The following loop is not necessary */
/* The employees will be saved together with the company */
/*
foreach (var employee in company.Employees)
{
context.AddToEmployees(employee);
}*/
context.SaveChanges();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With