With Entity Framework I'm trying to set up a many to many relationship in a simple blog asp.net mvc 4 app. My models are as follows:
public class BlogPost
{
[Key]
public string Id { get; set; }
public DateTime DateCreated { get; set; }
[Required]
public string Title { get; set; }
public string Image { get; set; }
public string ThumbImage { get; set; }
public ICollection<BlogCategory> Categories { get; set; }
[AllowHtml]
public string Content { get; set; }
}
public class BlogCategory
{
[Key]
public string Name { get; set; }
public virtual ICollection<BlogPost> Posts { get; set; }
}
The blog categories cannot be an enum as new ones may want to be added, so a collection is needed. The Category is simple, just the name, and a way to navigate to all posts with the given category. The problem is when creating a new BlogPost. In an ideal world the following would happen.
private BlogPost post = new BlogPost
{
Title = "Blog Entry One",
Categories = new List<BlogCategory>()
{
new BlogCategory {Name = "Web"},
new BlogCategory() {Name = "C#"}
},
Content =
"Aliquam sem quam, posuere eget tellus in, porta semper dolor. Morbi aliquam placerat urna ut."
};
When the context is saved if a BlogCategory with the name "Web" is already in the database then reference to it. If not create the new entry.
At the moment EF throws an error that the key is already in use. Hope someone can help!