views:

62

answers:

1

I have a problem to resolve here:

At the highest layers, we work with a dto. We use Entity framework in the Data layer, working with the entities, converting the results as dtos.

We have some custom searches being done in the upper layers, the question is: how to translate these lambda expressions between classes, assuming that each property have the same name and type?

+1  A: 

Can you write an interface that contains the common properties, have the relevant classes implement that interface, and then rewrite the lambdas against it?

Edit: since you can't do that, this gets a lot more complicated. I see two options:

  1. Generate the expression trees from scratch at runtime (a lot of work, especially if your lambdas are complex, and error-prone besides);

  2. Write an interface and modify the lambdas as I originally suggested, and then at runtime use an ExpressionVisitor to replace the lambda's parameter expression with a new parameter expression referring to your class type, and replace references to the original parameter expression with references to the new parameter expression.

I'd strongly prefer 2, since you can continue to write the lambdas in code; at runtime, you're just doing a relatively simple replacement in the expression tree. It's a single solution for whatever lambdas you have now and come up with in the future.

Ben M
Yeah man, for a moment I forgot interfaces exists... I'll try to do it using a interface, thanks ;)
Victor Rodrigues
In fact I think I can't. Entity Framework uses some classes for relationships I can't make them compliant with POCO interfaces.
Victor Rodrigues