实体框架4,使用外键值插入而不是ID
我确信这是一个非常基本的问题,但现在让我感到困惑:
我有 2 个表,学生和带有外键约束的课程,许多学生到 1 个课程。
我在学生表中存储了 CourseId_FK 引用,因此当我创建学生时,我如何能够执行类似的操作?
Students student = new Students();
student.Name = Bob;
student.Course.CourseName = "Geography";
db.SaveChanges();
现在,上述方法不起作用,我必须解决
student.CourseId = 22;
任何人都可以帮助我吗?
谢谢
大卫
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您不想加载完整的课程实体:
这只会从数据库中获取地理课程的
Id
(如果没有的话会崩溃)。If you don't want to load the full course entity:
This would only fetch the
Id
of the Geography course from DB (or crash when there isn't any).查看您的实体,“学生”是否具有“课程”(实际上:课程)属性?
对于您想要执行的操作,您的实体可能看起来像这样:
然后您需要执行以下操作:
编辑:如果学生只能上一门课程,则修改
Student< /code> 类,所以它看起来像这样:
那么你的代码看起来像这样:
你的代码发生了什么(我期望)是你只有
CourseId
所以当你这样你就可以' t 为您的学生分配实际的课程对象。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:
Then you'd do something like:
Edit: If the Student can only have one course, you modify the
Student
class so it looks like this:Then your code looks like this:
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:
Update: the answer is about the situation when a student has zero or one course (as in the provided code).