LINQ to Entities无法识别我的方法

时间:2016-06-06 16:09:51

标签: c# linq-to-entities linq-method-syntax

我想在LINQ选择中将日期和时间转换为波斯语,但linq无法识别我的方法:

  

LINQ to Entities无法识别方法'System.String toPersianDateTime(System.DateTime)'方法,并且此方法无法转换为商店表达式。

如何将我的方法更改为LINQ兼容?

我的方法:

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;
}

我的LINQ代码:

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 个答案:

答案 0 :(得分:6)

EF无法将您的自定义方法转换为SQL。您可以注入.AsEnumerable()调用以将基础上下文从EF更改为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 }
                    );