【问题标题】:Inserting records on multiple tables in a single method using Entity Framework使用实体框架以单一方法在多个表上插入记录
【发布时间】:2019-11-02 06:06:38
【问题描述】:

我在实体框架中使用代码优先方法,我想知道下面的代码是否有效?如果是这样,是否建议在单个表中添加多个表上的记录 使用实体框架的方法?请给我们您的想法。谢谢

 public void InsertRecords(Student student, Teacher teacher, Parent parent)
 {
     context.Students.Add(student);
     context.Teachers.Add(teacher);
     context.Parents.Add(parent);
 }

【问题讨论】:

  • 您缺少 CommitChanges

标签: c# entity-framework linq linq-to-sql linq-to-entities


【解决方案1】:

虽然您会在这个主题上得到几个不同的答案,但如果该方法适合您对程序的需求,那么请继续使用一种方法来插入记录。虽然它可能第一次工作,但当您需要更新 Student TeacherParent 模型时可能会遇到问题,因为您不能简单地根据您的 Primary/Foreign Key Relations 添加两次“相同”记录。

我个人会将这三个模型分解成工厂方法,就像这样(我会发布一个示例,其余的可以遵循)

public class Teacher
{
    public void Insert(Teacher entity)
    {
         //Initialize DB context here
         context.Teachers.Add(entity);
         context.SaveChanges();
    }

   public void Update(Teacher entity)
   {
         //Initialize DB context here
         context.Teachers.Attach(entity);
         context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
         context.SaveChanges();
   }
}

此代码不是您在应用程序中应具有的逐行代码,但它为您如何插入和更新基于工厂类的记录奠定了坚实的基础。您将需要合并错误处理和成功报告,但我想向您介绍如何在原始帖子中打破 InsertRecords 方法。

【讨论】:

  • 感谢您的意见,但我想确认一下。是否能够以一种方法将记录保存到所有 3 个表中?对吗?
  • @timmack 是的,您的插入记录方法现在可以包含所有三个工厂方法。而不是做context.Teachers.Add,你可以使用Teachers.Insert(Teacher)Students.Insert(student)Parent.Insert(parent),而所有三个表都在一个方法中被引用。实际的插入/更新发生在 3 种不同的方法中。这将有助于更好的调试和 OOP。这有意义吗?
  • 太棒了...我理解您对将模型分解为工厂方法的担忧,但我之所以会为多个表执行单一插入方法是有目的的。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-31
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
  • 1970-01-01
  • 2015-07-05
  • 2015-04-19
相关资源
最近更新 更多