【问题标题】:adding List of objects to Context in ef将对象列表添加到 ef 中的 Context
【发布时间】:2010-12-14 11:19:18
【问题描述】:

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

感谢帮助

【问题讨论】:

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


    【解决方案1】:

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

    db.companies.AddRange(newCompanies);
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        使用 linq 和一些 lambda,您可以像这样轻松地播种它。

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

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

        【讨论】:

          【解决方案4】:

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

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

          如果你想使用循环,你将使用导航属性Student,如果你想将Subjects表中的所有Subjects实例添加到对应的Student中,你将使用导航属性Subjects

          如何使用? 假设您有准备映射的对象,我的意思是您已在 Student 和 Subjects 中添加了字段。

          现在 student.Subjects = subjects' then add student using yourDbContext` 正如上面@Yakimych 的回答所解释的那样(尽管有评论)。

          我没有在 EF 中实现这一点,而是在 EF Core 3.1 中实现。但是,大多数未来的读者都会从这个答案中受益,包括那些使用 EF 而不是 EF Core 的读者。

          【讨论】:

            【解决方案5】:

            是的,你可以,就像

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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2017-11-30
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-09-01
              相关资源
              最近更新 更多