我遇到了异常 无法将类型“MySomeTypeThatImplementsISomeInterfaceAndIsPassedAs[T]ToTheClass”转换为类型“ISomeInterface”。 LINQ to Entities 仅支持转换实体数据模型基元类型。
我的存储库看起来像
public interface IRepository<T>
{
IQueryable<T> Get(System.Linq.Expressions.Expression<System.Func<T, bool>> Query);
}
另外,我还有服务类
public abstract class FinanceServiceBase<TAccount, TParcel, TPayment>
where TAccount : IAccount
where TParcel : IParcel
where TPayment : IPayment
{
//...
IRepository<TPayment> ParcelRepository {get; private set;}
public bool MakePayment(TPayment payment)
{
//...
ParcelRepository.Get(p => p.ParcelId == 2);
// here my exception is thrown
// **p.ParcelId is in IParcel**
//...
}
}
//...
通过这个类(class),我可以控制许多有关财务的事情,而无需重写其他程序的代码。我用 3 个通用参数完成了该类,因为我无法使用 IRepository,因为我的存储库不能是 <out T>
ParcelId 为 Int32
TParcel 是 typeof(ParcelToReceive),它是实现 IParcel 的实体,并且是使用 codeonly 生成的
当我调用 Get 并且生成的 lambda 看起来像这样时,就会出现问题
(**(ISomeInterface)**$p).SomeInterfaceMember ==
而不是
($p.SomeInterfaceMember)
因此, Entity Framework 尝试进行转换并抛出异常。我想知道的是:是否有办法告诉 linq lambda 字段 p.ParcelId 来自 TParcel 而不是来自 IParcel。
已经尝试过(没有运气):
p => ((TParcel)p).ParcelId
谢谢
最佳答案
似乎将通用约束从 where TAccount : IAccount
设置为 where TAccount : class, IAccount
告诉 Entity Framework 该表达式包含一个类 并且它不会像对原始 EDM 和枚举类型那样进行显式转换。
关于c# - 根据接口(interface)生成表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3613701/