我在我的通用类中有以下方法:
// This is the class declaration
public abstract class BaseService<TEntity, TKey> : IBaseService<TEntity, TKey> where TEntity : class, IEntity<TKey>
// The Method
public IQueryable<TEntity> GetActive()
{
if (typeof(IActivable).IsAssignableFrom(typeof(TEntity)))
{
return this.repository.Get().Cast<IActivable>()
.Where(q => q.Active)
.Cast<TEntity>();
}
else
{
return this.Get();
}
}
这是界面:
public interface IActivable
{
bool Active { get; set; }
}
基本上,
TEntity
是一个实体(POCO)类,如果它们有 Active
属性,就可以实现 IActivable 接口。我希望这个方法返回所有 Active
值为 true 的记录。但是,我遇到了这个错误:无法将类型 'WebTest.Models.Entities.Product' 强制转换为类型 'Data.IActivable'。LINQ to Entities 仅支持向 EDM 基元或枚举类型进行强制转换。我明白为什么会出现这个错误。但是 SO 上的文章没有任何适用于我的情况的有效解决方案。是否可以使用
Cast
或其他方式来实现?注意:我不想转换为 IEnumerable
,我想保留 IQueryable
。