title: Insert data in another table through entity framework MVC
body: <p>I want to save student's data in student table and their address in student details table i can't insert data in second table.</p>
  
  <p><strong>Error is Object reference not set to an instance of an object.</strong></p>
  
  <p><strong>Student Model</strong></p>
  
  <pre><code>public partial class Student
  {
      public int Id { get; set; }
      public string Name { get; set; }
      public Nullable&lt;System.DateTime&gt; CreatedDate { get; set; }
  }
  </code></pre>
  
  <p><strong>StudentDetails</strong></p>
  
  <pre><code>public partial class StudentDetail
  {
      public int Id { get; set; }
      public string Address { get; set; }
      public Nullable&lt;System.DateTime&gt; CreatedDate { get; set; }
  }
  </code></pre>
  
  <p><strong>View Model</strong></p>
  
  <pre><code>public class StudentViewModel
  {
      public Student Students { get; set; }
  
      public StudentDetail StudentDetails { get; set; }
  
  }
  </code></pre>
  
  <p><strong>DbSet</strong></p>
  
  <pre><code>public partial class SampleEntities : DbContext
  {
      public SampleEntities()
          : base("name=SampleEntities")
      {
      }
  
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          throw new UnintentionalCodeFirstException();
      }
  
  
      public System.Data.Entity.DbSet&lt;Basics.Models.Student&gt; Students { get; set; }
  
      public System.Data.Entity.DbSet&lt;Basics.Models.StudentDetail&gt; StudentDetails { get; set; }
  }
  </code></pre>
  
  <p><strong>Controller</strong></p>
  
  <pre><code>private SampleEntities db = new SampleEntities();
  </code></pre>
  
  <p><strong>Action</strong></p>
  
  <pre><code>[HttpPost]
  [ValidateAntiForgeryToken]
  public ActionResult Create(StudentViewModel model)
  {
      if (ModelState.IsValid)
      {
          model.Students.CreatedDate = DateTime.Now;
          db.Students.Add(model.Students);
          db.SaveChanges();
          //The Newly created Id gets created and when saving that Id in anothr table the exception comes  
          model.StudentDetails.Id = model.Students.Id;
          //For Time Being in real time it won't be hard coded  
          model.StudentDetails.Address = "New Jersey";
          db.StudentDetails.Add(model.StudentDetails);
          db.SaveChanges(); 
          return RedirectToAction("Index");
      }
  
      return View(model.Students);
  }
  </code></pre>