adding List of objects to Context in ef
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();
Using linq and some lambdas you can seed it easily like this.
Note: Regarding your current version you can do
List<Company> companies = new List<Company>();
companies.ForEach(n => context.AddToCompanies(n));
This is the way I do with Entity Framework 4.1 or higher with the Code First Approach
List<RelationshipStatus> statuses = new List<RelationshipStatus>()
{
new RelationshipStatus(){Name = "Single"},
new RelationshipStatus(){Name = "Exclusive Relationship"},
new RelationshipStatus(){Name = "Engaged"},
new RelationshipStatus(){Name = "Married"},
new RelationshipStatus(){Name = "Open Relationship"},
new RelationshipStatus(){Name = "Commited Relationship"}
};
statuses.ForEach(n => myContext.RelationshipStatuses.Add(n));
myContext.SaveChanges();
The Context was Setup as follows
public class MyContext:DbContext
{
public DbSet<RelationshipStatus> RelationshipStatuses{ get; set; }
}