這是基於前一個問題我有:EF Code First implemented interface property通用約束和表達式類型評價
我有這樣的事情。
interface IKeywordedEntity
{
ICollection<Keyword> Keywords { get; }
}
class Foo : EntityBase, IKeywordedEntity
{
public virtual ICollection<Keyword> Keywords { get { ... } }
}
EntityBase
的細節並不重要。
起初,我寫了這個擴展方法讓事情幹:
public static void WithKeywords<TEntityType>(this EntityTypeConfiguration<TEntityType>
entityTypeConfiguration) where TEntityType : EntityBase, IKeywordedEntity
{
entityTypeConfiguration.HasMany(e => e.Keywords).WithMany();
}
我會調用它像這樣:
modelBuilder.Entity<Foo>.WithKeywords();
然而,實體框架或C#編譯器是在lambda治療e
作爲IKeywordedEntity
而不是TEntityType
。這嚇壞了實體框架。
瞭解了這一點,我嘗試了手動將lambda作爲Expression
寫入HasMany
。我想出了以下內容:
public static void WithKeywords<TEntityType>(this EntityTypeConfiguration<TEntityType>
entityTypeConfiguration) where TEntityType : EntityBase, IKeywordedEntity
{
var rootExpression = Expression.Parameter(typeof (TEntityType));
var expression = Expression.Property(rootExpression, "Keywords");
entityTypeConfiguration.HasMany(Expression.Lambda<Func<TEntityType, ICollection<Keyword>>>(expression, rootExpression)).WithMany();
}
現在的智能感知正顯示出我的EntityBase
和IKeywordedEntity
組合正確,並告訴我說,e
是TEntityType
。
我的問題是:爲什麼通過/編譯表達式樹從lambda對待e
爲IKeywordedEntity
,而不是TEntityType
?