This is pretty basic question I am sure but it's baffling me now :S
I have 2 tables, Students and Courses with a foreign key constraint, Many Students to 1 Course.
I store in my Students table a CourseId_FK reference, so when I am creating a Student how would I be able to do something like this?
Students student = new Students();
student.Name = Bob;
student.Course.CourseName = "Geography";
db.SaveChanges();
Right now, the above doesn't work and I have to resolve to
student.CourseId = 22;
Can anyone help me pls?
Thanks
David
If you don't want to load the full course entity:
Student student = new Student();
student.Name = Bob;
student.CourseId = db.Courses
.Where(c => c.CourseName == "Geography")
.Select(c => c.CourseId).First();
db.SaveChanges();
This would only fetch the Id
of the Geography course from DB (or crash when there isn't any).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With