在ef中添加对象列表到Context

gru*_*ber 27 .net c# entity-framework entity-framework-4

是否可以在不使用foreach addObject的情况下在实体框架中向Context添加对象列表?

感谢帮助

nav*_*een 35

从EntityFramework 6可以像这样使用DbSet.AddRange方法(IEnumerable)

db.companies.AddRange(newCompanies);
Run Code Online (Sandbox Code Playgroud)


Yak*_*ych 16

通常你不能这样做 - 你必须循环.但是,在某些情况下,您可以避免添加每个对象 - 特别是,如果您有实体图并添加父节点.例如,如果您的Company对象具有以下集合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();
Run Code Online (Sandbox Code Playgroud)


Max*_*der 9

使用linq和一些lambdas你可以像这样轻松播种.

注意:关于您当前的版本,您可以这样做

List<Company> companies = new List<Company>();

companies.ForEach(n => context.AddToCompanies(n));
Run Code Online (Sandbox Code Playgroud)

这是我使用Code First方法实现Entity Framework 4.1或更高版本的方式

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();
Run Code Online (Sandbox Code Playgroud)

上下文设置如下

public class MyContext:DbContext
{
     public DbSet<RelationshipStatus> RelationshipStatuses{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)