将IQueryable数据集与MVC和Entity Framework连接起来

时间:2013-02-06 23:49:27

标签: c# asp.net-mvc linq

我正在使用Visual Studio 2010,C#和Entity Framework 5.我正在生成一个JSON结构,它是LINQ查询的结果。在控制器中我有以下内容:

[HttpPost]
public ActionResult ICD10ConditionSearch(string ICD10SearchTerm)
{
    CommonCodeEntities dataContextCommonCodes = new CommonCodeEntities(ConnectionString);

    IQueryable<ICD10Codes> codes = dataContextCommonCodes.ICD10Codes.
        Where(m => m.ICD10CodeTitle.Contains(ICD10SearchTerm));
    return Json(codes);
}

这样可以正常工作并返回预期的结果。

真正想要做的是使用lst搜索词并将结果连接起来。当我使用以下内容时:

[HttpPost]
public ActionResult ICD10ConditionSearch(string ICD10SearchTerms)
{
    String[] terms = ICD10SearchTerms.Split(' ');
    IQueryable<ICD10Codes> codes = Enumerable.Empty<ICD10Codes>().AsQueryable();
    IQueryable<ICD10Codes> codeLocal;            

    CommonCodeEntities dataContextCommonCodes = new CommonCodeEntities(ConnectionString);

    foreach (var term in terms)
    {
        codeLocal = dataContextCommonCodes.ICD10Codes.Where(m => m.ICD10CodeTitle.Contains(term));
        codes = codes.Concat(codeLocal);
    }
    return Json(codes);
}

这会生成以下错误This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code。我尝试过Concat()的其他变种,结果相同。

1 个答案:

答案 0 :(得分:1)

删除foreach并尝试:

[HttpPost]
public ActionResult ICD10ConditionSearch(string ICD10SearchTerms)
{
    String[] terms = ICD10SearchTerms.Split(' ');
    CommonCodeEntities dataContextCommonCodes = new CommonCodeEntities(ConnectionString);
    IQueryable<ICD10Codes> codes = dataContextCommonCodes.ICD10Codes
       .Where(e => terms.Any(k => e.ICD10CodeTitle.Contains(k)).AsQueryable();

    return Json(codes);
}

为什么你不使用List<ICD10Codes>的{​​{1}}个身份?