使用 Entity Framework 以单一方法在多个表中插入记录
Inserting records on multiple tables in a single method using Entity Framework
我在 entity framework 中使用代码优先方法,我想知道下面的代码是否有效?如果是这样,是否建议在单个表中添加多个表的记录
使用 entity framework 的方法?请给我们您的想法。谢谢
public void InsertRecords(Student student, Teacher teacher, Parent parent)
{
context.Students.Add(student);
context.Teachers.Add(teacher);
context.Parents.Add(parent);
}
虽然关于这个主题您会得到几个不同的答案,但如果该方法适合您对程序的需要,那么请务必继续使用一种方法来插入记录。虽然它可能第一次工作,但当您需要更新 Student
Teacher
或 Parent
模型时,您可能会 运行 遇到问题,因为您不能简单地添加 'Same'根据你的Primary/Foreign Key Relations
.
录制两次
我个人会像这样将三个模型分解成工厂方法(我会 post 一个例子,其余的可以遵循)
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();
}
}
此代码不是您应该在应用程序中逐行编写的代码,但它是您如何基于出厂 类 插入和更新记录的坚实基础。您将需要合并错误处理和成功报告,但我想让您大致了解如何在原始 post.
中分解 InsertRecords 方法
我在 entity framework 中使用代码优先方法,我想知道下面的代码是否有效?如果是这样,是否建议在单个表中添加多个表的记录 使用 entity framework 的方法?请给我们您的想法。谢谢
public void InsertRecords(Student student, Teacher teacher, Parent parent)
{
context.Students.Add(student);
context.Teachers.Add(teacher);
context.Parents.Add(parent);
}
虽然关于这个主题您会得到几个不同的答案,但如果该方法适合您对程序的需要,那么请务必继续使用一种方法来插入记录。虽然它可能第一次工作,但当您需要更新 Student
Teacher
或 Parent
模型时,您可能会 运行 遇到问题,因为您不能简单地添加 'Same'根据你的Primary/Foreign Key Relations
.
我个人会像这样将三个模型分解成工厂方法(我会 post 一个例子,其余的可以遵循)
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();
}
}
此代码不是您应该在应用程序中逐行编写的代码,但它是您如何基于出厂 类 插入和更新记录的坚实基础。您将需要合并错误处理和成功报告,但我想让您大致了解如何在原始 post.
中分解 InsertRecords 方法