[EntityFramework] 查詢結果將字串轉成列舉

在EntityFramework5後若你希望Entity的欄位是列舉型別,預設支援數值欄位例:int16 int32 Byte等。但若欄位是字串時,該如何處理?
如下的列舉是對應的Char型別
    public enum TrCodes
    {
        A = 'A',
        O = 'O',
        S = 'S',
        T = 'T',
        P = 'P',
    }
試著在查詢時將Entity的欄位轉成列舉
image

得到的結果是收到一個Linq的錯誤"LINQ to Entities 無法辨識方法 "
image


解決方法

查詢前先將列舉變成一個資料集
            var trCodes = from name in Enum.GetNames(typeof(TrCodes))
                          select (TrCodes)Enum.Parse(typeof(TrCodes),name);

再將原本查詢與列舉資料集作Join,完整如下
 var trCodes = from name in Enum.GetNames(typeof(TrCodes))
                          select (TrCodes)Enum.Parse(typeof(TrCodes),name);

            var result = from o in this.db.INVMAH
                         join c in trCodes on o.TR_CODE equals c.ToString()
                         select new InvMahInfo
                         {
                             TRNO = o.TRNO,
                             TrCode = c,
                            
                         };

用SqlProfiler觀察SQL,是將列舉集合Select成一個子查詢Table來使用

image

參考來源

http://stackoverflow.com/questions/10494704/convert-string-to-enum-in-linq-to-sql

這個網誌中的熱門文章

IIS 設定只允許特定IP進入