在ef中添加对象列表到Context
是否可以在不使用foreach addObject的情况下在entity framework中向Context添加对象列表?
感谢帮助
通常你不能这样做 – 你必须循环。 但是,在某些情况下,您可以避免添加每个对象 – 特别是,如果您有实体图并添加父节点。 例如,如果您有一个具有Employees
集合的Company
对象:
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();
从EntityFramework 6可以像这样使用DbSet.AddRange方法(IEnumerable)
db.companies.AddRange(newCompanies);
使用linq和一些lambdas你可以像这样轻松播种。
注意:关于您当前的版本,您可以这样做
List companies = new List (); companies.ForEach(n => context.AddToCompanies(n));
这是我使用Code First方法实现Entity Framework 4.1或更高版本的方式
List statuses = new List () { 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();
上下文设置如下
public class MyContext:DbContext { public DbSet RelationshipStatuses{ get; set; } }
是的,你可以,像
List empList = this.context.Employee.ToList();