0

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!

4

1 回答 1

2

您需要先检索 Category 实体并重新使用,或者将它们附加到上下文并重新使用。否则 EF 将尝试在数据库中为新创建的实体创建新行,这将由于键冲突而失败。

于 2013-08-29T23:09:14.087 回答