adding List of objects to Context in ef

2019-04-18 09:31发布

问题:

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

thanks for help

回答1:

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


回答2:

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

db.companies.AddRange(newCompanies);


回答3:

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; }
}


回答4:

Yes you can, like

List<Employee> empList = this.context.Employee.ToList();