从linq查询调用函数时出错

时间:2011-09-30 17:41:22

标签: c# linq linq-to-sql generics

这里是我写的代码,一旦我添加了调用第二个函数ValidCodes = GetValidCodes(bv.Variable_Id)

的行,我就会收到错误
public IQueryable<BvIndexRow> GetBenefitVariableIndex(int healthPlanId)
{
    var q = from bv in Db.BenefitVariables
            where bv.Private == "N" || (bv.Private == "Y" && bv.Health_Plan_ID == healthPlanId)
            join bao in Db.baObject on bv.Variable_Id equals bao.ba_Object_id
            join servicetype in Db.BenefitVariableServiceTypes.Where(bvst => bvst.Key_Service_Type == "Y" && bvst.isActive == 1) 
            on bv.Variable_Id equals servicetype.Variable_Id into groupedBvst
            where bv.isActive == 1 && bao.isActive == 1 
            from bvst in groupedBvst.DefaultIfEmpty()
            select new BvIndexRow
            {
                // some code here too
                ValidCodes = GetValidCodes(bv.Variable_Id)
            };
    return q;
}

public string GetValidCodes(int varID)
{
    // some code here
    return "None";
}

2 个答案:

答案 0 :(得分:2)

Linq to Sql无法将方法调用GetValidCodes(..)解析为数据库上下文中的操作 - 一旦将结果带回内存或者填写相应的linq,就必须填写该属性直接到sql语句。

答案 1 :(得分:2)

另一张海报回答了原因,但没有回答。原因是Linq-to-SQL无法将方法调用转换为SQL,因为它不是SQL的一部分!这非常有意义!所以解决这个问题的一个简单方法是:

public IQueryable<BvIndexRow> GetBenefitVariableIndex(int healthPlanId)
{
   var q = (... your query ...
      select new BvIndexRow
      {
         Type = (bv.Private.ToLower() == "y" ? "Private " : "Public ") + (bao.ba_system_variable_ind ? "System" : "Benefit"),
         Class = bv.Variable_Classification,
         ServiceType = bvst.Service_Type.Service_Type_Name ?? string.Empty,
         LineOfBusiness = bv.LOB,
         Status = bv.Status.ToLower() == "p" ? "Production" : "Test",
         Name = bao.ba_object_Code,
         Description = bao.ba_Object_Desc,
         Id = bv.Variable_Id,
      }).ToArray();

   foreach (var bvIndexRow in q) {
      bvIndexRow.ValidCodes = GetValidCodes(bvIndexRow .Variable_Id);
   }

   return q;
}

这应该让你想要你想要的!

编辑:通过,你可能还想在你的BvIndexRows列表上调用.ToList()或.ToArray()。这具有导致立即评估的效果并且将阻止多次枚举。如果您不想立即评估,您可能需要编辑您的问题以解释为什么会出现这种情况。我在上面的示例中添加了.ToArray(),但我也想解释原因!