adding List of objects to Context in ef

雨燕双飞 提交于 2020-01-01 07:28:28

问题


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


来源:https://stackoverflow.com/questions/4438574/adding-list-of-objects-to-context-in-ef

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!