Entity Framework 4, inserting with foreign key value not ID

﹥>﹥吖頭↗ 提交于 2019-12-05 10:07:47

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

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!