【问题标题】:Code First one to many relationship and category with parent categoryCode First 与父类别的一对多关系和类别
【发布时间】:2015-04-21 11:57:20
【问题描述】:
public class Category
{
    [Key]
    public int CategoryId { get; set; }
    public int ParentCategoryId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int Status { get; set; }
    public virtual ICollection<Category> ParentCategories { get; set; }
    public virtual ICollection<ImageSet> ImageSets { get; set; }

    [ForeignKey("ParentCategoryId")]
    public virtual Category ParentCategory { get; set; }
}    

public class ImageSet
{
    [Key]
    public int ImageSetId { get; set; }
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string InsertDate { get; set; }
    public int Status { get; set; }
    public virtual ICollection<Image> Images { get; set; }

    [ForeignKey("CategoryId")]
    public virtual Category Category { get; set; }
}

public class Image
{
    [Key]
    public int ImageId { get; set; }
    public int ImageSetId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string ImageUrl { get; set; }
    public string ThumbImageUrl { get; set; }
    public string InsertDate { get; set; }
    public int Status { get; set; }

    [ForeignKey("ImageSetId")]
    public virtual ImageSet ImageSet { get; set; }
}

Context:
    public DbSet<Category> Categories { get; set; }
    public DbSet<Image> Images { get; set; }
    public DbSet<ImageSet> ImageSets { get; set; }

错误页面:在表 'ImageSets' 上引入 FOREIGN KEY 约束 'FK_dbo.ImageSets_dbo.Categories_CategoryId' 可能 导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。可以 不创建约束。查看以前的错误。

有什么问题?

【问题讨论】:

    标签: entity-framework ef-code-first code-first entity-framework-migrations


    【解决方案1】:

    你需要添加这个:

    modelBuilder.Entity<ImageSet>()
    .HasRequired(is => is.Category)
    .WithMany(c => c.ImageSets)
    .WillCascadeOnDelete(false);
    

    这里有很好的解释为什么会发生这种情况:

    https://stackoverflow.com/a/19390016/1845408

    https://stackoverflow.com/a/17127512/1845408

    【讨论】:

    • 很高兴帮助兄弟 ;) @RamazanSağır
    • Eyvallah hocam, Allah razı olsun... Şu mecraya da Türkçe serpiştirelim biraz。 :D
    猜你喜欢
    • 1970-01-01
    • 2012-08-21
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    相关资源
    最近更新 更多