【问题标题】:Call a method inside LINQ Query在 LINQ 查询中调用方法
【发布时间】:2013-01-09 08:37:38
【问题描述】:

我有一个自定义模型的 LINQ 查询。我只是想使用一种方法来为模型属性赋值。但是当我尝试使用自定义模型时,它会抛出一些类似这样的错误消息:

LINQ to Entities 无法识别方法 'System.String GetPONo(Ent, System.String)' 方法,并且该方法无法转换为存储表达式。

代码

var model = (from p in db.PoDetails
             select new porders
             {
                 Category = p.Category,
                 PONO = GetPONo(p, p.Category),
              }).ToList();

方法

public string GetPONo(PoDetail p, string ASD)
{
    if (ASD == "B")
    {
        var PoNo = (from pord in db.Porders where pord.Id == p.PoId select pord.No).FirstOrDefault();
        return PoNo;
    }
    else
    {
        var PoNo = (from porder in db.Porders
                    where porder.Id == (from rec in db.RecommendResources where rec.Id == p.BibId select rec.PoId).FirstOrDefault()
                    select porder.No).FirstOrDefault();
        return PoNo;
    }
}

【问题讨论】:

    标签: asp.net-mvc-3 linq c#-4.0


    【解决方案1】:

    这是因为 LINQ to Entities 在后台被转换为 SQL。当然,SQL 中没有GetPONo(p, p.Category) 方法,因此您的代码将失败。您可以通过调用 ToList() 来强制查询在您的 select 之前运行来解决此问题。

    var model = (from p in db.PoDetails select p).ToList();
    model = from m in model
            select new porders
            {
                Category = m.Category,
                PONO = GetPONo(m, m.Category)
            };
    

    你可以看看我对类似问题的回答here

    【讨论】:

      【解决方案2】:

      您可以根据类别值使用三元运算符对 PONO 进行不同的子查询

      var model = (from p in db.PoDetails
                   select new porders
                   {
                       Category = p.Category,
                       PONO = p.Category == "B" ?
                              (from pord in db.Porders 
                               where pord.Id == p.PoId 
                               select pord.No).FirstOrDefault() :
                              (from porder in db.Porders
                               where porder.Id == (from rec in db.RecommendResources 
                                                   where rec.Id == p.BibId 
                                                   select rec.PoId).FirstOrDefault()
                               select porder.No).FirstOrDefault()
                   }).ToList();
      

      您也可以为此创建存储过程。

      【讨论】:

        猜你喜欢
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多