尝试建立递归关系的EF 6.1错误 - 自引用表和FluentAPI

时间:2014-09-08 22:02:33

标签: c# entity-framework foreign-key-relationship ef-fluent-api

我在尝试在Entity Framework 6.1中创建递归关系时遇到了很多问题。

我需要一些不同类型的类别,但是已经创建了一个" base"所有这些的抽象类。我使用Table-Per-Type层次策略。类别可能有也可能没有ParentCategory。 (如果没有,那么它是顶级类别)

在下面的代码中,我展示了我是如何创建抽象类类以及ParentCategory和ChildCategories导航属性的。我已将ParentCategoryId设为可空,因为在顶级类别的情况下不需要它。我已经看到了一些我正在尝试实现的帖子,尽管我认为我已经解决了所有问题,但我仍然遇到以下错误:

  

Category_ParentCategory ::多重性与角色' Category_ParentCategory_Target'中的参照约束冲突。在关系' Category_ParentCategory'。由于“从属角色”中的所有属性都是不可为空的,因此主要角色的多样性必须为“' 1

我想知道它是否与Category是一个抽象类有关,而且我正在使用添加的继承模型,因为我还没有看到任何其他帖子中的确切用法这种类型的递归关系。任何帮助表示赞赏!

public abstract class Category : ICategory
{
    protected Category()
    {           
        ChildCategories = new HashSet<Category>();
    }

    public int CategoryId { get; private set; }
    public int? ParentCategoryId { get; set; }
    public virtual Category ParentCategory { get; set; }
    public virtual ICollection<Category> ChildCategories { get; set; }
}



public class WLCategory : Category, IWLCategory
{
    public WLCategory() : base()
    {
        DynamicFields = new HashSet<DynamicFieldDef>();
    }
    public virtual ICollection<DynamicFieldDef> DynamicFields { get; set; } 
}

使用FluentAPI,我已经配置了数据库创建:

class CategoriesConfig : EntityTypeConfiguration<Category>
{
    public CategoriesConfig()
    {          
        HasOptional(p => p.ParentCategory).WithMany(p => p.ChildCategories)
            .HasForeignKey(p => p.ParentCategoryId);

        ToTable("Categories");
    }
}



class WLCategoriesConfig : EntityTypeConfiguration<WLCategory>
{
    public WLCategoriesConfig()
    {
        HasKey(p => p.CategoryId);
        ToTable("WLCategories");
    }
}

1 个答案:

答案 0 :(得分:0)

好的,发现了这个问题!在我的OnModelCreating方法中,我设置了一些全局配置,其中一个是:

 modelBuilder.Properties().Configure(p => p.IsRequired());

我希望默认情况下将所有属性设置为不可为空,除非我在逐个类的基础上明确覆盖属性。但是,我并不认为此全局设置适用于以下数据类型:

int? (nullable int)

显然,我错了。 (不确定为什么EF会尝试在DB中使一个可空的int不可为空,即使开发人员全局设置了IsRequired .int?的固有含义是“可空的”。)我必须明确地将以下代码行添加到我的HasOptional语句之前的CategoriesConfig类:

 Property(p => p.ParentCategoryId).IsOptional();

现在,一切都很顺利。 : - )