Reputation: 3018
With automatic database recreation, it is uncertain whether referred entities will get loaded or not.
The context is EF CTP 5 and ASP.NET MVC 2. In the global.asax a database initializer is set that forces recreation of the database every time the application starts up.
Successfully retrieving an entity from a context in a controller action may still cause null reference errors when traversing references even if the references are marked as required (not null in the database). Turning off lazy loading does not make any difference.
This behaviour cannot be reproduced reliably but was observed on two different workstations (XP, 7) using Cassini.
Below are the models. Null reference exception is thrown when trying to access the NewsProvider
property of the NewsFeed
object. It makes no difference taking off the virtual qualifier.
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; }
}
Upvotes: 1
Views: 228
Reputation: 12440
This is just a guess, but complex types can NEVER be null. So if you have any reference to a complex type (ICollection) you should initialize them from the Entity constructor.
Example:
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; }
}
For more info, here is a great blog post: http://weblogs.asp.net/manavi/archive/2010/12/11/entity-association-mapping-with-code-first-part-1-one-to-one-associations.aspx
Upvotes: 1