问题
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:
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).
回答2:
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.
回答3:
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).
来源:https://stackoverflow.com/questions/6113570/entity-framework-4-inserting-with-foreign-key-value-not-id