EF 6 Fluent配置 - 使用父级TPH递归嵌套对象

时间:2013-07-15 22:30:43

标签: entity-framework ef-code-first fluent-interface

我有以下实体,它有一个自己的集合和一个父属性,如果它是根小部件我想要为null:

public class CanvasWidgetQuery
{
    public int CanvasWidgetId { get; set; }

    public int? ParentCanvasWidgetId { get; set; }
    public virtual CanvasWidgetQuery ParentCanvasWidget { get; set; }
    public virtual ICollection<CanvasWidgetQuery> InnerCanvasWidgets { get; set; }

}

因为CanvasWidgetQuery实际上只是一个基类(可能也是抽象的,但是在我看到它没有它之前我不会抽象)。我想创建一个通用映射配置来映射CanvasWidgetQuery的派生类型:

public class CanvasWidgetQueryMap<TCanvasWidgetQuery> : EntityTypeConfiguration<TCanvasWidgetQuery>
    where TCanvasWidgetQuery : CanvasWidgetQuery
{
    public CanvasWidgetQueryMap() 
    {
        this.HasKey(q => q.CanvasWidgetId);

        this.HasMany(w => w.InnerCanvasWidgets)
            .WithOptional(w => w.ParentCanvasWidget)
            .HasForeignKey(w => w.ParentCanvasWidgetId);

    }
}

无论派生类型如何,它们都具有这些属性,但不幸的是它抱怨WithOptional调用(一次有2个错误):

 Error  1   Cannot implicitly convert type 'CanvasWidgetQuery' to 'TCanvasWidgetQuery'. An explicit conversion exists (are you missing a cast?) 


 Error  2   Cannot convert lambda expression to delegate type 'System.Func<CanvasWidgetQuery,TCanvasWidgetQuery>' because some of the return types in the block are not implicitly convertible to the delegate return type  

如果我将其向上移动到实际派生类型的映射:

 public class SearchCanvasWidgetQueryMap : CanvasWidgetQueryMap<SearchCanvasWidgetQuery>
{
    public SearchCanvasWidgetQueryMap() 
    {
        this.HasMany(w => w.InnerCanvasWidgets)
            .WithOptional(w => w.ParentCanvasWidget)
            .HasForeignKey(w => w.ParentCanvasWidgetId);
    }
}

现在它抱怨它同时不能将CanvasWidgetQuery转换为SearchCanvasWidgetQuery

public class SearchCanvasWidgetQuery : CanvasWidgetQuery
{

}

我怎样才能完成我追求的目标

1 个答案:

答案 0 :(得分:2)

您是否尝试为包含定义层次结构的属性的基类定义地图?

e.g:

public class CanvasWidgetQueryMap<CanvasWidgetQuery> : EntityTypeConfiguration<CanvasWidgetQuery>
{
    public CanvasWidgetQueryMap() 
    {
        this.HasKey(q => q.CanvasWidgetId);

        this.HasMany(w => w.InnerCanvasWidgets)
            .WithOptional(w => w.ParentCanvasWidget)
            .HasForeignKey(w => w.ParentCanvasWidgetId);

    }
}

答案中有一些很好的附加信息:CTP 4 doesn't consider base class properties如果上述内容无法实现您的目标,可能会有所帮助。