Inserting using a foreign key value rather than an ID in Entity Framework 4

c# entity-framework foreign-key-relationship

Question

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

1
5
5/24/2011 4:43:34 PM

Accepted Answer

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

5
5/24/2011 4:41:20 PM

Popular Answer

Looking at your entities, does "Student" have a "Course" (Really: Courses) property?

Your entity should probably look something like this, for what you want to do:

public class Student
{
    public string Name {get; set;}

    public virtual ICollection<Course> Courses {get; set;}
}

Then you'd do something like:

Student student = new Student();
student.Name = Bob;
student.Courses.Add(db.Courses.Where(c => c.CourseName == "Geography"));

Edit: If the Student can only have one course, you modify the Student class so it looks like this:

public class Student
{
    public int StudentId {get; set;}
    public string Name {get; set;}
    public int CourseId {get; set;}
    public virtual Course Course {get; set;}
}

Then your code looks like this:

student.Course = db.Courses.Where(c => c.CourseName == "Geography"));

What's going on with your code (I expect) is that you only have the CourseId so when you're so you can't assign an actual course object to your student.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow