实体框架多对多关系:插入时出错

时间:2014-06-24 20:57:40

标签: entity-framework ef-code-first

我需要以下两个类来建立多对多关系:

public class ContentItem
{
  public int ContentItemId {get; set; }
  public virtual ICollection<Category> Categories {get; set; }
  // Other properties...
}

public class Category
{
  public int CategoryId {get; set; }
  public string CategoryName {get; set; }
  // Other properties
}

我有以下EntityTypeConfiguration类:

public class ContentItemConfiguration : EntityTypeConfiguration<ContentItem>
{
    public ContentItemConfiguration()
    {
        Property(_ => _.ContentItemId)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        HasMany(_ => _.InterestCategories)
            .WithMany()
            .Map(_ =>
            {
                _.ToTable("ContentItemCategory", "CMS");
                _.MapLeftKey("ContentItemId");
                _.MapRightKey("CategoryId");
            });
    }
}

当我为上述配置添加迁移时,会创建相应的表和FK。然后我尝试使用以下代码进行插入:

        var itemToAdd = new ContentItem
        {
          // Set various properties here
        };

        itemToAdd.Categories.Add(dbContext.Categories.First());

        dbContext.ContentItems.Add(itemToAdd);
        dbContext.SaveChanges();

当我调用SaveChanges时,我最终会遇到以下异常:

  

System.InvalidOperationException:ReferentialConstraint中的依赖属性映射到存储生成的列。列:'ContentItemId'。

我已经检查过,我可以看到ContentItemId应该存储生成(身份)的唯一地方位于内容表中。 EF脚手架的连接表有一个ContentId列,但它没有设置为标识,所以我不确定我的映射出错了。任何建议将不胜感激。

0 个答案:

没有答案