在ef中添加对象列表到Context

时间:2010-12-14 11:19:19

标签: c# .net entity-framework entity-framework-4

是否可以在实体框架中将对象列表添加到Context而不使用foreach addObject?

感谢您的帮助

5 个答案:

答案 0 :(得分:30)

从EntityFramework 6中,您可以像这样使用DbSet.AddRange Method (IEnumerable)

db.companies.AddRange(newCompanies);

答案 1 :(得分:14)

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

答案 2 :(得分:9)

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

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

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

companies.ForEach(n => context.AddToCompanies(n));

这是我使用代码优先方法 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();

上下文设置如下

public class MyContext:DbContext
{
     public DbSet<RelationshipStatus> RelationshipStatuses{ get; set; }
}

答案 3 :(得分:0)

您可以通过导航属性进行操作。我遇到了同样的问题,使用循环感觉不太好。

如果您有一个学生表和一个主题表。表学生和表主题之间将分别具有一对多的关系。学生表中的导航属性为public IEnumerable<Subject> Subjects {get; set;},主题表中的导航属性为public Student Student {get;set;}

如果要使用循环,将使用导航属性Student,如果要在Subjects表中将所有Subject实例与相应的Student添加在一起,则将使用导航属性{{1} }。

如何使用? 假设您有准备映射的对象,我的意思是您已在“学生”和“主题”中添加了字段。

现在 Subjects DbContext` 如上面@Yakimych答案中所述(虽然有评论)。

我尚未在EF Core 3.1中实现此功能。但是,包括使用EF而不是EF Core的答案在内,大多数将来的读者都会从此答案中受益。

答案 4 :(得分:-6)

是的,你可以,比如

List<Employee> empList = this.context.Employee.ToList();
相关问题