基于接口生成的表达式 [英] Expression generated based on interface

查看:95
本文介绍了基于接口生成的表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了异常
无法将类型 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**
         //...
     }
 }
 //...

通过此类,无需重写其他程序的代码,我就可以控制财务方面的许多事情。我使用3个通用参数完成了该类,因为我不能使用IRepository,因为我的存储库不能< out T>

With this class I can control many things about finances without rewrite code for other programs. I've did the class with 3 generic parameters because I couldn't use IRepository because my repository can't be <out T>

ParcelId是Int32

TParcel是typeof( ParcelToReceive ),它是实现 IParcel 的实体em>,并且是使用codeonly生成的。

ParcelId is Int32
TParcel is typeof(ParcelToReceive) that is an entity who implement IParcel, and was generated with codeonly

当我调用Get时,会出现问题,并且生成的lambda看起来像

The problem occurs when I call Get and the resultant lambda looks like

(**(ISomeInterface)**$p).SomeInterfaceMember == 

而不是

($p.SomeInterfaceMember)

因此,实体框架尝试进行强制类型转换并引发异常。我想知道的是:是否仍然要告诉linq,lambda字段p.ParcelId来自 TParcel ,而不是来自 IParcel

so, entity framework try do the cast and throws the exception. What I want to know is: is there anyway to tell linq that the lambda field p.ParcelId is from TParcel and not from IParcel.

已经尝试过(没有运气):

Already tried (with no luck):

p => ((TParcel)p).ParcelId 

谢谢

推荐答案

似乎将通用约束从其中TAccount:IAccount 设置为类似 where TAccount: IAccount 类告诉实体框架该表达式包含一个 class ,并且不会像原始EDM和枚举类型那样进行显式转换。

It seems that setting the generic constraints from where TAccount : IAccount to something like where TAccount : class, IAccount tells entity framework that the expression contains a class and it will not make the explicit cast that it would do for primitive EDM and enum types.

这篇关于基于接口生成的表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆