I have two entities: Student and Enrollement having a one-to-many relationship. The entities looks like
public class Student{
[Key]
public int Studentid {get; set;}
public string fname{get; set;}
public string lname{get; set;}
public virtual ICollection<Enrollement> Enrollement_E{ get; set; }
}
public class Enrollement{
[Key]
public int EnrolId {get; set;}
[ForeignKey("Studentid ")]
public int Student{get; set;}
public string kk{get; set;}
public virtual Student Student_E { get; set; }
}
Studentid is an autoincremented primary key and serve as foreign key in the enrollment table. I am trying to insert data into both table. Both inserts should not commit if either 1 fails. So, I have the following code.
try{
repository.stu.insert(new student{fname = "fname", lname="lname"});
repository.enr.insert(new Enrollement{student=???, kk="test"});
}
finally{
repository.save();
}
How am I supposed to pass in the foreign key to the Enrollement record when the data has not been saved. Or is there another way of doing this?
Instead of assigning the foreign key, assign the whole object:
try{
var student = new student(){fname = "fname", lname="lname"};
repository.stu.insert(student);
repository.enr.insert(new Enrollement(){Student_E = student});
}
finally{
repository.save();
}
This way when student
get's its new key it'll be autosaved into Enrollment.
Ef easily handle foreign key to insert data to multiple related tables. if you want to insert your data simultaneously in two tables you can use below code for insert:
student st = new student
{
fname = "fname",
lname= "lname",
Enrollement_E=new List<Enrollement>
{
new Enrollement{kk="something"}
}
};
repository.student.Add(st);
repository.SaveChanges();
Ef itself makes foreign key for second table