I try to write a Blog with MVC4 and have problems with the Post - Comment (1 to n), as well as with the Post - Tag (n to m) relationship, using code first.
Tag:
public class Tag
{
[Key]
[Required]
public int ID { get; set; }
[Required]
public string Name { get; set; }
public IList<Post> Posts { get; set; }
}
Comment:
public class Comment
{
[Key]
[Required]
public int ID { get; set; }
[Required]
public string Name { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
public DateTime DateTime { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string Body { get; set; }
}
Post:
public class Post
{
[Key]
[Required]
public int ID { get; set; }
[Required]
public string Title { get; set; }
[Required]
public DateTime DateTime { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string Body { get; set; }
public IList<Tag> Tags { get; set; }
public IList<Comment> Comments { get; set; }
}
Using this code first, I get a database which looks like:
Comment n to 1 Post n to m Tag
Where for the n to 1 the foreign key to Post is in Comment and for the n to m a Cross Table was created.
Now, I created a Controller as well as a View to create a new Post with Tags.
When I look into my database, everything is filled correctly. The Post and Tags exist, and the Cross Table is filled with the IDs.
But now, when I want to render the Post in my View I want to get the data with @post.Tags, where @post represents my currently selected Post which has the correct Data (Title, Name etc), but for Tags, which is the IList<Tag> from my Model I get a NullPointer Exception. (The same goes for @post.Comments)
Although, when creating the Post:
new Post() { ID = -1, Tags=new List<Tag>(), Comments=new List<Comment>(), DateTime = DateTime.Now };
Edit:
When using virtual, I get a System.Data.EntityCommandExecutionException. There is already an open DataReader associated with this Command which must be closed first
Solution
I was missing the virtual Keyword as well as to invoke the Include Method. To get the Method I had to use System.Data.Entity
Now it works, thank you both