Cast linq results to List

前端 未结 3 1591
囚心锁ツ
囚心锁ツ 2021-01-02 07:45

I have extended my entities to implement specific interfaces for its type. I am trying to perform the following query:

 var results = from x in context.MyEnt         


        
相关标签:
3条回答
  • 2021-01-02 08:21

    You can do the cast on the client, bypassing the entity framework query translation layer by calling AsEnumerable extension method:

    return results.Any()
           ? results.AsEnumerable().Cast<IApplicationEntity>().ToList() 
           : null;
    

    However, it's better to reverse the order of doing the Count check:

    var list = results.AsEnumerable().Cast<IApplicationEntity>().ToList();
    return list.Count == 0 ? null : list;
    
    0 讨论(0)
  • 2021-01-02 08:21
    return results.Count() > 0 ? 
    results.Select(result => (IApplicationEntity)result)
    .ToList() : null;
    
    0 讨论(0)
  • 2021-01-02 08:33

    If you want to cast your results to a complex type, you need to force the code to use LINQ to Objects rather than LINQ to Entities.

    Calling the AsEnumerable extension method before the cast is the trick here.

    Try the following:

    var results = from x in context.MyEntityTable
                  where x.AProperty == AValue
                  select x;
    
    return results.AsEnumerable().Cast<IApplicationEntity>().ToList();
    

    Also note that it's not wise to check Count() on the enumerable, since it means the collection is iterated over twice.

    0 讨论(0)
提交回复
热议问题