LINQ to Entities无法识别该方法,并且此方法无法转换为存储表达式

时间:2017-05-12 22:04:31

标签: asp.net-mvc linq

我有一个动作:

           var viewModel = (from o in db.Sepet
                         join q2 in db.Urunler on o.urun_id equals q2.urun_id
                         join m in db.Markalar on q2.marka_id equals m.marka_id
                         where (o.sepet_id == bskt_id && o.statu == 0)
                         select new SepetView
                         {
                             urun_id = q2.urun_id,
                             urun_resmi = q2.resimlink,
                             urun_link = q2.urun_link,
                             urun_adi = q2.urun_adi,
                             urun_fiyat = FiyatGetir(q2.gununfirsati,q2.urun_fiyat,q2.kampanyafiyati),
                             adet = o.adet,
                             sepettutari = (o.adet * FiyatGetir(q2.gununfirsati, q2.urun_fiyat, q2.kampanyafiyati)),
                             marka_adi = m.marka_adi,

                         }).ToList();

并有一个方法(FiyatGetir):

        public static decimal FiyatGetir(DateTime tarih,decimal urunfiyat,decimal kampanyalifiyat)
    {
        decimal fiyat;
        if (tarih == DateTime.Now)
            fiyat = kampanyalifiyat;
        else
            fiyat = urunfiyat;
        return fiyat;
    }

它给出了一个错误:LINQ to Entities无法识别方法,.....并且此方法无法转换为商店表达式。

我该如何解决?

1 个答案:

答案 0 :(得分:1)

括号之间的所有内容都是表达式。实体框架将尝试将整个表达式转换为SQL,这意味着表达式的每个部分(标记)必须具有到SQL等效项的显式映射。当然,对于FiyatGetir,没有这样的映射,因为它是一种未知的方法(对于EF)。

如评论中所述,将逻辑移入LINQ查询本身并不困难,但需要两次,因此最好使用let关键字:

var viewModel = (from o in db.Sepet
                 join q2 in db.Urunler on o.urun_id equals q2.urun_id
                 join m in db.Markalar on q2.marka_id equals m.marka_id
                 where (o.sepet_id == bskt_id && o.statu == 0)
                 let fiyat = q2.gununfirsati == DateTime.Today 
                                              ? q2.kampanyafiyati
                                              : q2.urun_fiyat
                 select new SepetView
                 {
                     urun_id = q2.urun_id,
                     urun_resmi = q2.resimlink,
                     urun_link = q2.urun_link,
                     urun_adi = q2.urun_adi,
                     urun_fiyat = fiyat,
                     adet = o.adet,
                     sepettutari = (o.adet * fiyat),
                     marka_adi = m.marka_adi,

                 }).ToList();

请注意,我将参考日期/时间更改为DateTime.Todayq2.gununfirsati完全等于DateTime.Now的几率为零,所以我认为这是不正确的。也许你应该在比较之前截断q2.gununfirsatiDbFunctions.TruncateTime)。