Peter Smith
Peter Smith

Reputation: 5550

concatenating IQueryable data sets with MVC and Entity Framework

I am using Visual Studio 2010, C# and Entity Framework 5. I am generating a JSON structure which is the result of a LINQ query. In the controller I have the following:

[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);
}

This works correctly and returns the expected results.

What I really want to do is to use a lst of search terms and concatonate the result. When I use the following:

[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 generate the following error This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code. I have tried other variants of Concat() with the same result.

Upvotes: 0

Views: 1290

Answers (1)

Jalal
Jalal

Reputation: 6856

Remove foreach and try this:

[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);
}

Why you just don't use List<ICD10Codes> instate of IQueryable<ICD10Codes>?

Upvotes: 1

Related Questions