【发布时间】:2012-11-05 11:12:48
【问题描述】:
我正在尝试使用 Entity Framework 5 进行具有多对多关系的简单插入。
我有两个 POCO 类如下。
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; }
}
还有下面流畅的api映射代码……
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);
}
}
实体框架随后将生成 Category 和 Article 表以及第三个映射表,其详细信息在 ArticleMap 代码 (MapArticleCats) 中指定,在 SQL Server 中如下所示。
ArticleID - 整数
类别ID -int
以下代码(给或取几行)将类别添加到我的控制器中的文章。
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);
}
这似乎在插入时产生了一些奇怪的行为。它将向类别表 (DUPLICATE) 插入一个新类别,并将新创建的 CategoryID(而不是原始 id)和正确的 ArticleID 插入到 MapArticleCats 表中。
谁能看出我哪里出错了?
【问题讨论】:
标签: asp.net-mvc entity-framework-5