简体   繁体   中英

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

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"));

If the Student can only have one course, you modify the Student class so it looks like this:如果学生只能有一门课程,则修改Student class ,使其如下所示:

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.

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

I'd do something like this:

Student student = new Student();
student.Name = Bob;
student.Course = db.Courses.First(c => c.CourseName == "Geography");
db.SaveChanges();

Update: the answer is about the situation when a student has zero or one course (as in the provided code).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM