Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression generated based on interface

I'm geting the exception Unable to cast the type 'MySomeTypeThatImplementsISomeInterfaceAndIsPassedAs[T]ToTheClass' to type 'ISomeInterface'. LINQ to Entities only supports casting Entity Data Model primitive types.

my repository looks like

public interface IRepository<T>
{
    IQueryable<T> Get(System.Linq.Expressions.Expression<System.Func<T, bool>> Query);
}

Also, I have the service class

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**
         //...
     }
 }
 //...

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 is Int32
TParcel is typeof(ParcelToReceive) that is an entity who implement IParcel, and was generated with codeonly

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

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

instead of

($p.SomeInterfaceMember)

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 

Thanks

like image 950
Davi Fiamenghi Avatar asked Aug 31 '10 22:08

Davi Fiamenghi


1 Answers

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.

like image 75
Davi Fiamenghi Avatar answered Sep 28 '22 13:09

Davi Fiamenghi