Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorporate Enum.GetName(...) into Linq Query

I have the enumeration:

public enum CmdType {
    [Display(Name = "abc")]
    AbcEnumIdentifier = 0,

    [Display(Name = "xyz")]
    XyzEnumIdentifier = 1,
    ...
}

I'd like to get the names of each enumeration into my query, but even using .WithTranslations() I'm getting this error:

LINQ to Entities does not recognize the method 'System.String GetName(System.Type, System.Object)' method, and this method cannot be translated into a store expression.

The query:

var joinedRecord =
    (
        from m in mTable
        join b in bTable on m.Id equals b.aRefId
        select new {
            aId = a.Id,
            aAttrib1 = a.Attrib1
            ...
            bCmdType = Enum.GetName(typeof(CmdType), b.CmdType)
        }
    ).WithTranslations();

How do I return a generated value using Enum.GetName(...) within the query?

like image 933
Jasel Avatar asked Dec 11 '15 18:12

Jasel


1 Answers

LINQ to entities tries to translate your query to SQL and it fails to do so, because there is no equivalent of the Enum.GetName method in SQL.

You need to materialize the results of the query and convert the enum values to their name in the memory.

var joinedRecords = (
    from m in mTable
        join b in bTable on m.Id equals b.aRefId
        select new {
            aId = a.Id,
            aAttrib1 = a.Attrib1
            ...
            bCmdType = b.CmdType
        }
).AsEnumerable() //Executes the query, further you have simple CLR objects
.Select(o => new {
    aId = o.Id,
    aAttrib1 = o.Attrib1
    ...
    bCmdTypeName = Enum.GetName(typeof(CmdType), o.CmdType)
});
like image 187
Lukas Kabrt Avatar answered Oct 05 '22 16:10

Lukas Kabrt