asp.net mvc - Insert data in another table through entity framework MVC -


i want save student's data in student table , address in student details table can't insert data in second table.

error object reference not set instance of object.

student model

public partial class student {     public int id { get; set; }     public string name { get; set; }     public nullable<system.datetime> createddate { get; set; } } 

studentdetails

public partial class studentdetail {     public int id { get; set; }     public string address { get; set; }     public nullable<system.datetime> createddate { get; set; } } 

view model

public class studentviewmodel {     public student students { get; set; }      public studentdetail studentdetails { get; set; }  } 

dbset

public partial class sampleentities : dbcontext {     public sampleentities()         : base("name=sampleentities")     {     }      protected override void onmodelcreating(dbmodelbuilder modelbuilder)     {         throw new unintentionalcodefirstexception();     }       public system.data.entity.dbset<basics.models.student> students { get; set; }      public system.data.entity.dbset<basics.models.studentdetail> studentdetails { get; set; } } 

controller

private sampleentities db = new sampleentities(); 

action

[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 , when saving id in anothr table exception comes           model.studentdetails.id = model.students.id;         //for time being in real time won't hard coded           model.studentdetails.address = "new jersey";         db.studentdetails.add(model.studentdetails);         db.savechanges();          return redirecttoaction("index");     }      return view(model.students); } 

why not have

public studentdetail studentdetails { get; set; } 

in student class , change id for

public int studentid { get; set; }  

and change id in studentdetail also

public int studentid { get; set; }  

like entity framework able join them in 1 1 relationship. you'll have add primary keys/foreign keys depending on needs.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -