I'm using Entity Framework 6 (POCO, code first approach) and I have the following situation...
I have an entity that has a property which is an enumeration (called Status) - the value in the database is an integer and what I want to do is show to the user a localized description of this value.
I, therefore, have code that looks like this (actually, it calls into a ResourceManager
and there are more status values but it is indicative):
public static string ToDisplayable(Status status)
{
switch(status)
{
case Status.One:
return "Status ONE";
case Status.Two:
return "Status TWO";
default:
return "Unknown Status";
}
}
...
var results = someIqueryable
.ToList()
.Select(r => new
{
Status = r.Status,
DisplayableStatus = ToDisplayable(r.Status)
});
Now, that works fine, because of course the good ol' toList
has meant that all my stuff's been pulled back from the database before the Select
is called. If I remove the ToList
I get the following exception of course:
An exception of type 'System.NotSupportedException' occurred in mscorlib.dll but was not handled in user code
Additional information: LINQ to Entities does not recognize the method 'System.String ToDisplayable(Status)' method, and this method cannot be translated into a store expression.
OK, fair enough, it is not able to translate my function call to SQL and I don't really blame it.
The thing is I really, really, really don't want that ToList
in there because later on some Where
clauses may (or may not) be added and, besides, I just don't need all the columns on my entity.
I think, therefore, that my only option is to do this:
var results = someIqueryable
.Select(r => new
{
Status = r.Status,
DisplayableStatus = r.Status == Status.One
? "Status ONE"
: r.Status == Status.Two
? "Status TWO"
: "Unknown Status"
});
That is kind of ugly and tedious (there are about 15 status values in my real code) and, worst of all, I cannot reuse it (but it does work at least).
The beauty of the simple method at the beginning was that, because there are other entities with Status columns, that have the same possible values I could just call the same method. Now if I add a new status value for example I have to go a huntin' through my code for all the places that do this translation. Horrible.
So, does anyone know how I can create a reusable piece of code that can be translated to a SQL expression that I can plug into a Select
method?
Can I weave some magic with an Expression
perhaps?