Search code examples
entity-frameworklinq-to-entitiescompiled-query

Linq-to-Entities match ID in list of integers in a compiled query


I'm trying to find a way to implement a Linq-to-Entities compiled query of the form:

Func<MyEntities, List<int>, IQueryable<MyClass>> query = System.Data.Objects.CompiledQuery.Compile(
    (MyEntities entities, List<int> IDs) => (
         (from au in entities.Mine where IDs.Any(x => x == au.ID) select au)
    ));

Because only scalar parameters can be passed to CompiledQuery.Compile the above fails. I'm trying to find some clever way to pass a comma delimited list of integers as a string and use that in the L2E query along the lines of:

Func<MyEntities, string, IQueryable<MyClass>> query = System.Data.Objects.CompiledQuery.Compile(
    (MyEntities entities, string IDs) => (
         (from au in entities.Mine where IDs.Split(',').Any(x => Convert.ToInt32(x) == au.ID) select au)
    ));

But that doesn't work due to the unsupported Split function.

Any clever ideas about how this could be implemented?


Solution

  • I ended up finding a way to do it but it's way too slow at around 3s.

    string ids = "|" + String.Join("|", new List<int> { 4, 5, 6, 7, 8, 9, 10, 20, 23, 34 }) + "|";   
    
    Func<MyEntities, string, IQueryable<MyClass>> query =     System.Data.Objects.CompiledQuery.Compile(
    (MyEntities entities, string IDs) => (
         (from au in entities.Mine where IDs.Contains("|" + SqlFunctions.StringConvert((decimal)au.ID).Trim() + "|")select au)
    )); 
    

    Back to the drawing board.