Include Enum.GetName (...) in Linq Query

I have an enumeration:

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

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

I would like to get the names of each enumeration in my query, but even using .WithTranslations(), I get this error:

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

Request:

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 to return a generated value using Enum.GetName(...)in a query?

+4
source share
3 answers

Enum.GetName(typeof(CmdType), b.CmdType), SQL, Enum , , , int Enum .

:

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 = b.CmdType
    }
)
.AsEnumerable() // or ToList()
.Select( // map to another type calling Enum.GetName(typeof(CmdType), b.CmdType) )
.WithTranslations();

, , AsEnumerable() ToList(), IQueryable<T> ( , , ). , , , #, .

+2

LINQ SQL, , SQL Enum.GetName.

.

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)
});
+4

Try casting in AsEnumerable () so you can use LINQ to Objects. LINQ to Entities will try to translate it to SQL, for which there is no equivalent:

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

See http://www.lavinski.me/ef-linq-as-emumerable/

+2
source

Source: https://habr.com/ru/post/1619551/


All Articles