【发布时间】:2012-02-10 14:30:21
【问题描述】:
我正在尝试使用实体框架的代码优先方法构建一个类似于非常基本的电子邮件系统的 ASP.NET MVC 4 Web 应用程序。为了演示我遇到的问题,请考虑以下 C# 类。
public class Message
{
public int Id { get; set; }
[Required]
public User From { get; set; }
[Required]
public User To { get; set; }
[Required]
public string Subject { get; set; }
[Required]
public string Content { get; set; }
[Required]
[DataType(DataType.DateTime)]
public DateTime CreatedAt { get; set; }
public bool IsRead { get; set; }
public bool IsTrash { get; set; }
public bool IsSpam { get; set; }
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Password { get; set; }
public ICollection<Role> Roles { get; set; }
public string Email { get; set; }
}
为数据库播种后,第一个消息列如下所示:
Id Subject Content CreatedAt IsRead IsTrash IsSpam From_Id To_Id
1 Howdy Lorem 2012-02-10 0 0 0 2 1
Users 表中存在两个具有上述 ID 的用户。
如果我运行以下 LINQ,它会显示该消息的 From 和 To 均为 null,但所有其他字段均已正确填充:
dbContext.Messages.Single(o=>o.Id==1);
我做错了什么会导致这两个字段为空?这可能是我的班级组织中的一个缺陷吗?
【问题讨论】:
-
dtryon 是正确的。您缺少虚拟关键字。
标签: c# asp.net-mvc asp.net-mvc-3 entity-framework ef-code-first