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

时间:2013-04-04 13:03:13

标签: c# asp.net-mvc entity-framework linq-to-entities

我使用实体框架工作在我的数据库中调用了一些日期。但我的下面的代码给出了这个错误

LINQ to Entities无法识别方法'SchoolBreifcase.Compliance get_Item(Int32)'方法,并且此方法无法转换为商店表达式。

这是我的完整代码

FinancialCompliance financialCompliance = new FinancialCompliance();
            List<Compliance> compliance = null;
            if (HttpContext.Current.User.IsInRole("SchoolAdmin"))
            {

                compliance = datamodel.Compliances.Where(u => u.UserId == userId).OrderBy(c => c.AddedDate).ToList();

            }
            if (HttpContext.Current.User.IsInRole("User"))
            {
                compliance = datamodel.Compliances.Where(u => u.VerifierId == userId || u.OwnerId == userId).OrderBy(c => c.AddedDate).ToList();
            }
            if (compliance != null)
            {
                for (int i = 1; i < compliance.Count; i++)
                {
                    financialCompliance = datamodel.FinancialCompliances.Where(f => f.ComplianceId == compliance[i].ComplianceId).SingleOrDefault();
                    if (compliance.Count == i)
                    {
                        return financialCompliance;
                    }
                }
            }
            return financialCompliance;
        }

这一行给出了错误:

financialCompliance = datamodel.FinancialCompliances.Where(f => f.ComplianceId == compliance[i].ComplianceId).SingleOrDefault();

无法帮助堆叠流量回答

我在这个堆栈溢出站点找到了一些答案

LINQ to Entities does not recognize the method

等.. 但对我没有帮助。所以我问了这个问题。请不要因为已经被问过的原因而关闭这个问题

2 个答案:

答案 0 :(得分:13)

您需要创建一个变量来引用compliance[i].ComplianceId,然后再使用它。

for (int i = 1; i < compliance.Count; i++)
{
    var complianceId = compliance[i].ComplianceId;
    financialCompliance = datamodel.FinancialCompliances.Where(f => f.ComplianceId == complianceId ).SingleOrDefault();
    if (compliance.Count == i)
    {
        return financialCompliance;
    }
}

答案 1 :(得分:11)

关于compliance[i].ComplianceId。首先创建一个变量:

var id = compliance[i].ComplianceId;

financialCompliance = datamodel.FinancialCompliances
                      .Where(f => f.ComplianceId == id).SingleOrDefault();