c# - How to insert a record into a table with a foreign key using Entity Framework in ASP.NET MVC -
i'm new entity framework code-first. learning in asp.net mvc, using code-first database creation.
i have 2 classes:
public class student { public int studentid { get; set; } public string name { get; set; } public int standard { get; set; } public int subjectid { get; set; } [foreignkey("subjectid")] public icollection<subject> subjects { get; set; } } public class subject { [key] public int subjectid{ get; set; } public string subjectname { get; set; } } i'm trying insert student record student table, has foreign key subjectid referencing subject table.
i'm trying out in 2 possible ways:
first approach
using(var cxt = new schoolcontext()) { subject sub = new subject() { subjectid = 202, subjectname ="geology" }; student stu = new student() { name = "riya", subjectid = 202 }; cxt.subjects.add(sub); cxt.students.add(stu); cxt.savechanges(); } here created new subject instance, has subjectid=202. when create student object , assign value 202 subjectid, there insert statement conflict. though there subject subjectid = 202, why there insert conflict? , when debug, see navigation property subjects null here. don't understand point here.
second approach:
using( var cxt=new schoolcontext()) { student stu = new student() { name = "riya" }; subject sub = new subject() { subjectid = 202, subjectname = "geology" }; stu.subjects.add(sub); cxt.students.add(stu); cxt.savechanges(); } but null reference exception
object reference not set instance of object
why stu.subjects null here?
so questions here are:
what
subjectidinstudentclass mean? i.e. value pertain to? can explicitly set it, if yes, refer primary key ofsubjecttable? if no, specified ef code conventions purpose?similarly: navigation property role? why null , when not null?
my basic understanding of navigation property is used make ef determine relationship between 2 entities.
can please clarify bit examples appreciated.
you're creating new student, , new subject, in both approaches. understand, you're trying do, create new student, , assign existing subject (with subjectid = 202) - right??
the subjectid in student class makes absolutely no sense in setup - since have 1:n relationship between student , subject. need use icollection<subject> handle 0:n subjects student enrolled in.
for - use code:
using(var ctx = new schoolcontext()) { // create *new* student student stu = new student() { name = "riya" }; // existing subject id=202 subject sub = ctx.subjects.firstordefault(s => s.subjectid == 202); // add existing subject new student's "subjects" collection stu.subjects.add(sub); // add new student context, , save all. ctx.students.add(stu); ctx.savechanges(); } that - new student inserted database table, , 1:n relationship between student , subjects established.
Comments
Post a Comment