Reputation: 24063
How can I do the following in linq to entities for entity framework::
public static Expression<Func<T, bool>> IsOk<T>(long? entityId)
{
return x => (!entityId.HasValue || entityId.Value == x.GetEntityId());
}
The x.GetEntityId()
returns an exception since it doesn't recognize the method.
Upvotes: 0
Views: 246
Reputation: 28869
I'll suggest your type parameter be restricted to a custom interface like IMyExpectation
which contains
interface IMyExpectation {
int GetEntityId();
}
And then constrain your method's type parameter to that interface. (Now this will compile as far as the GetEntityId
method goes.)
public static Expression<Func<T, bool>> IsOk<T>(long? entityId)
where T: IMyExpectation // << restrict the type to what is needed
{
return new Func<T, bool>(
x => !entityId.HasValue || entityId.Value == x.GetEntityId()
);
}
Then on the entity framework classes implement that interface where you need it, but on a partial
part of the class in a separate file so the model doesn't obliterate your custom code whenever the model is regenerated. e.g.
On your EF model entities
Note: This is subject to Aliostad's answer.
public partial class Customer : IMyExpectation { //...
public partial class Invoice : IMyExpectation { //....
// etc
Or, on your POCOs
Note: This should work fine if unencumbered by EF classes
public class CustomerPoco: IMyExpectation { //...
public class InvoicePoco : IMyExpectation { //...
Now your entities and classes (and whatever you implemented 'IMyExpectation' on) are all expressing themselves just as your original method wants.
Finally your method will understand any of these things you've implemented the interface on, and therefore they are all candidates to be passed to the method via its type parameter.
If yours is the right scenario for this answer, then that should wrap things up nicely.
Upvotes: 1
Reputation: 81660
You cannot - your database cannot run GetEntityId()
(since it does not understand it) hence your Linq provider cannot translate it.
So how can you solve it:
GetEntityId()
) then this needs to be done at the client: return all rows and do the filtering in C# subsequently. Of course it is needless to say what it is gonna do to your performance.Upvotes: 0