A.D.
A.D.

Reputation: 435

Linq to entities custom function in select

In Linq to Entities one can't use standard c# method to modify the results in the "select" clause, canonical functions are required.

I need to invoke such query:

CoreEntities.Contracts.Select(
c=> new {
   c.Name,
   c.Type,
   Role = MapToRole(c));

private string MapToRole(Contract contract) {
    switch(contract.Type) {
        case: CTypes.Main: return "somerole1";break;
        case: CTypes.Secondary: return "somerole2";break;
        // ... 
        default: break;
    }

    return "none";
}

The "MapToRole" is a C# method created just to declutter the linq query.

Is there a way to create a custom c# function that would be accepted by Entity Framework "linq to Entity" parser?

I've found a solution for query filters but not for data formatting.

Upvotes: 2

Views: 1303

Answers (1)

Oliver
Oliver

Reputation: 9002

It appears that as it's a simple transformation, there's no reason this needs to be translated by the provider. I would suggest simply adding AsEnumerable() before your Select() to "detach" your projection from the provider.

Alternatively you could have a CTypes property in your data type and a method/property that performs the transformation of that within your model.


As a side note, doing this particular transformation in your application layer means that you're only pulling through the enum value, not a string - therefore less data from the provider.

Upvotes: 2

Related Questions