LINQ to Entities does not recognize my method

佐手、 提交于 2019-11-28 06:02:19

问题


I want to convert date and time to Persian in LINQ select but linq can not recognize my method :

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

How can I change my method to LINQ compatible?

My method :

public static string toPersianDateTime(DateTime dt)
{
    PersianCalendar pc = new PersianCalendar();
    string pDateTime = pc.GetYear(dt).ToString() + "/" + pc.GetMonth(dt).ToString() + "/" + pc.GetDayOfMonth(dt).ToString() + " ";
    pDateTime += pc.GetHour(dt) + ":" + pc.GetMinute(dt) + ":" + pc.GetSecond(dt);
    return pDateTime;
}

And my LINQ code :

var result = (from ord in db.vw_orders
              where ord.uid == user.id
              orderby ord.order_date descending
              select new { ord.id,
                           date = Tools.toPersianDateTime((DateTime)ord.order_date),
                           ord.is_final, 
                           ord.status, 
                           ord.image_count, 
                           ord.order_count, 
                           ord.total_price });

回答1:


EF cannot translate your custom method to SQL. You can inject a .AsEnumerable() call to change the underlying context from EF to Linq-to-Objects:

var result = (from ord in db.vw_orders
              where ord.uid == user.id
              orderby ord.order_date descending select ord
             )
             .AsEnumerable()
             .Select(o => new { o.id,
                                date = Tools.toPersianDateTime((DateTime)o.order_date),
                                o.is_final, 
                                o.status, 
                                o.image_count, 
                                o.order_count, 
                                o.total_price }
                    );


来源:https://stackoverflow.com/questions/37662117/linq-to-entities-does-not-recognize-my-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!