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
Post a Comment