Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding List of objects to Context in ef

Is it possible to add list of object to Context in entity framework without using foreach addObject ?

thanks for help

like image 535
gruber Avatar asked Dec 14 '10 11:12

gruber


People also ask

How do I save a list of objects in Entity Framework?

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

How do I insert multiple rows in Entity Framework?

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.

How do I add a student entity using DB context?

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.


2 Answers

From EntityFramework 6 you can use DbSet.AddRange Method (IEnumerable) like this

db.companies.AddRange(newCompanies); 
like image 64
naveen Avatar answered Oct 13 '22 08:10

naveen


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();
like image 35
Yakimych Avatar answered Oct 13 '22 08:10

Yakimych