使用自动数据库娱乐,不确定引用的实体是否会被加载。
上下文是EF CTP 5和ASP.NET MVC 2.在global.asax中,设置了一个数据库初始化程序,每次启动应用程序时都会强制重新创建数据库。
成功从控制器操作中的上下文中检索实体在遍历引用时仍可能导致空引用错误,即使引用被标记为必需(在数据库中不为null)。关闭延迟加载没有任何区别。
此行为无法可靠再现,但在使用卡西尼号的两个不同工作站(XP,7)上观察到。
以下是型号。尝试访问NewsProvider
对象的NewsFeed
属性时,抛出空引用异常。取消虚拟限定符没什么区别。
public class NewsProvider
{
public int Id { get; set; }
[Required(ErrorMessage = "Please enter a name")]
[StringLength(50, ErrorMessage = "The name is too long")]
public string Name { get; set; }
}
public class NewsFeed
{
public int Id { get; set; }
[Required(ErrorMessage = "Please enter a name")]
[StringLength(50, ErrorMessage = "The name is too long")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter a URL")]
[StringLength(300, ErrorMessage = "The URL is too long")]
public string Url { get; set; }
[Required(ErrorMessage = "Please enter a news provider")]
public virtual NewsProvider NewsProvider { get; set; }
}
答案 0 :(得分:1)
这只是猜测,但复杂的类型永远不会为空。因此,如果您对复杂类型(ICollection)有任何引用,则应该从Entity构造函数初始化它们。
示例:
public class NewsProvider
{
public int Id { get; set; }
[Required(ErrorMessage = "Please enter a name")]
[StringLength(50, ErrorMessage = "The name is too long")]
public string Name { get; set; }
}
public class NewsFeed
{
public NewsFeed() {
//Never allow NewsProvider to be null
NewsProvider = new NewsProvider();
}
public int Id { get; set; }
[Required(ErrorMessage = "Please enter a name")]
[StringLength(50, ErrorMessage = "The name is too long")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter a URL")]
[StringLength(300, ErrorMessage = "The URL is too long")]
public string Url { get; set; }
[Required(ErrorMessage = "Please enter a news provider")]
public virtual NewsProvider NewsProvider { get; set; }
}
欲了解更多信息,这里有一篇很棒的博文: http://weblogs.asp.net/manavi/archive/2010/12/11/entity-association-mapping-with-code-first-part-1-one-to-one-associations.aspx