实体框架4,插入的外键值不是ID [英] Entity Framework 4, inserting with foreign key value not ID

查看:59
本文介绍了实体框架4,插入的外键值不是ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定这是一个非常基本的问题,但现在让我感到困惑:S

This is pretty basic question I am sure but it's baffling me now :S

我有2个表,有外键约束的Students和Courses,许多学生要1个课程。

I have 2 tables, Students and Courses with a foreign key constraint, Many Students to 1 Course.

我将一个CourseId_FK引用存储在学生表中,所以当我创建一个学生时,我将如何做这样的事情?

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;

有人可以帮助我吗?

谢谢

大卫

推荐答案

如果您不想加载完整课程实体:

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

这只会获取 Id 数据库提供的地理课程(或没有课程时会崩溃)。

This would only fetch the Id of the Geography course from DB (or crash when there isn't any).

这篇关于实体框架4,插入的外键值不是ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆