我有以下实体,它有一个自己的集合和一个父属性,如果它是根小部件我想要为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
{
}
我怎样才能完成我追求的目标
答案 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如果上述内容无法实现您的目标,可能会有所帮助。