I'm trying to do a simple insert with a many-to-many relationship using Entity Framework 5.
I have two POCO classes as follows.
public class Category
{
public virtual string Title { get; set; }
public virtual DateTime EntryDate { get; set; }
public virtual DateTime LastUpdated { get; set; }
public virtual ICollection<Article> Articles { get; set; }
}
public class Article
{
public virtual string Title { get; set; }
public virtual string Content { get; set; }
public virtual DateTime EntryDate { get; set; }
public virtual DateTime LastUpdated { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
And the following fluent api mapping code...
public class CategoryMap : EntityTypeConfiguration<Category>
{
public CategoryMap()
{
this.ToTable("Categories");
this.HasKey(x => x.ID);
this.Property(x => x.Title).IsRequired().HasMaxLength(255);
}
}
public class ArticleMap : EntityTypeConfiguration<Article>
{
public ArticleMap()
{
this.ToTable("Articles");
this.HasKey(x => x.ID);
this.HasMany(x => x.Categories)
.WithMany(x => x.Articles)
.Map(x =>
{
x.ToTable("MapArticleCats");
x.MapLeftKey("CategoryID");
x.MapRightKey("ArticleID");
});
this.Property(x => x.Title).IsRequired().HasMaxLength(255);
this.Property(x => x.Content).IsRequired().HasMaxLength(4000);
}
}
The entity framework will then generate both Category and Article tables along with a third mapping table of which details were specified in the ArticleMap code (MapArticleCats), which looks like the following in SQL Server.
ArticleID - int
CategoryID -int
The following code (give or take a few lines) adds the Categories to the Article in my controller.
IEnumerable<Category> GetCats = CategoryRepository.GetAll();
//DO SOME CODE TO FIGURE WHICH CATEGORIES I NEED.
IEnumerable<Category> Categories = InferCategoriesFromPostedData(Model.Categories, GetCats);
foreach (Category c in Categories)
{
Article.Categories.Add(c);
}
This seems to create some strange behavior on insert. It will insert a new category into the category table (DUPLICATE) and also insert the newly created CategoryID (instead of the original id) and the correct ArticleID to the MapArticleCats table.
Can anyone see where I've gone wrong?