Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4, inserting with foreign key value not ID

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

like image 908
DeveloperDavid Avatar asked May 24 '11 16:05

DeveloperDavid


1 Answers

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).

like image 145
Slauma Avatar answered Nov 14 '22 22:11

Slauma