2

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

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);
    }
}

现在它抱怨它不能同时转换CanvasWidgetQuerySearchCanvasWidgetQuery

public class SearchCanvasWidgetQuery : CanvasWidgetQuery
{

}

我怎样才能完成我所追求的

4

1 回答 1

2

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

例如:

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 不考虑基类属性,如果上述内容无法实现您所追求的,这可能会有所帮助。

于 2013-07-16T09:06:07.823 回答