【发布时间】:2014-05-03 17:40:17
【问题描述】:
我在这里遇到了一个非常奇怪的问题,我不知道为什么。
我应该在 C# 中制作小型 localdb 控制台应用程序。目标是在数据库中输入人员(实际上是教师),并提供一定数量的信息。
我有几个课程,但其中 2 个在这里很重要:认证和符号。 证书是教授的证书。
这些类的代码是这样的:
class Certification
{
public int CertificationID { get; set; }
public virtual Teacher Teacher { get; set; }
public virtual Course Course { get; set; }
public string CertificationName { get; set; }
public virtual Notation Notation { get; set; }
}
class Notation
{
public int NotationID {get;set;}
public string Note {get;set;}
}
没什么太危险的。通过迁移,我创建了我的数据库,它们看起来应该是这样的:
认证:
CertificationID (PK)
CertificationName
Course_CourseID (FK to another class, course)
Notation_NotationID (FK to notations)
Teacher_TeacherID (FK to the teachers)
符号:
NotationID (PK)
Note
我的程序允许我添加教师,并提供我需要的所有信息,例如他们的证书。在这里,我做了一些假老师,有假人证书。 如果我调用 SELECT * FROM Certification ,我得到的正是我应该得到的,像这样的一行:
CertificationID = 6
CertificationName = placeholder
Course_CourseID = 13
Notation_NotationID = 12
Teacher_TeacherID = 5
这一切都是正确的。 CourseID 链接到数据库中的实际课程,NotationID 链接到实际笔记中,Teacher 也链接到实际教师。一切都很好!
现在,我只想展示我们老师的证书:
var certifs = from c in db.Certifications where c.Teacher.TeacherID == item.TeacherID select c;
foreach(var v in certifs )
{
var course = (from c in db.Courses where c.CourseID == v.Course.CourseID select c).First();
var note = (from n in db.Notations where n.NotationID == v.Notation.NotationID select n.NotationID).First();
Console.WriteLine("Name: " + v.CertificationName + ", related to the " + course.CourseName + " course, with a note of " + note);
Console.WriteLine("");
}
而且它不起作用。当我的 foreach 循环开始时,我在循环中的第一项没有对符号的任何引用。其他一切都很好:课程和教师的外键都在这里,并且有效,但对于符号,我只得到一个空值。所以我的认证项看起来更像:
CertificationID = 6
CertificationName = placeholder
Course_CourseID = 13
Notation_NotationID = null
Teacher_TeacherID = 5
基本上,如果我执行 SQL 查询,我在数据库中的行非常好,但通过实体框架(和 LINQ)调用它会返回一个 null 值作为表示法。 (调用 var note 等时会抛出异常......
有人对此有任何想法吗?我真的被困在这上面了。
如果我的英语不够好,我很抱歉。如果你们需要更多信息,尽管问。
JC 回答:
延迟加载无法正常工作。急切加载解决了这个问题。
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
标签: c# linq entity-framework