timmack
timmack

Reputation: 590

Inserting records on multiple tables in a single method using Entity Framework

I'm using code first approach with entity framework and I would like to know if this code below will work? and if so, is it recommended to add records on multiple tables in a single method using entity framework? Kindly give us your thoughts. Thanks

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

Upvotes: 0

Views: 481

Answers (1)

davedno
davedno

Reputation: 349

While you will get several different answers on this topic, if that method suites your needs for the program then by all means go ahead and use one method to insert records. Although it may work the first time around, you may run into issues when you need to update a Student Teacher or Parent model since you cannot simply add the 'Same' record twice depending on your Primary/Foreign Key Relations.

Personally I would break the three models into factory methods like so (I will post one example and the rest can follow)

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

This code is not line for line what you should have in your application but it is a solid foundation as to how you can insert and update records based off factory classes. You will need to incorporate error handling and success reporting but I wanted to give you a general over view of how you can break out that InsertRecords method in your original post.

Upvotes: 1

Related Questions