Linq Entity Framework generic filter method

后端 未结 2 469
孤城傲影
孤城傲影 2020-12-19 20:33

I have some methods which perform a standard filter on data from my Entities (using Entity Framework v4).

Example #1:

protected IQueryable

        
相关标签:
2条回答
  • 2020-12-19 21:14

    I wanted to do the same thing with IQueryable<T> as an input parameter type for the generic method.

    I got the runtime exception of "Unable to cast the type.... LINQ to Entities only supports casting Entity Data Model primitive types".

    After some time I recognized, I forgot to add the class constraint for the generic parameter. However IQueryable<T> does not require to have the class constraint, it still needs that to resolve the types at runtime.

    It would have taken me hours, without this post. Thanks :)

    0 讨论(0)
  • 2020-12-19 21:25

    I'd say adding interfaces is a simpler option than messing with the expression tree or reflection. EF entities are partial classes, so you should be able to do something like:

    Updated to include class constraint (see Mark's comment)

    public interface IHideable
    {
      string State { get; }
      string Hidden { get; }
    }
    
    ...
    
    namespace Database
    {
      public partial class Product : IHideable { }
      public partial class Customer : IHideable { }
    }
    
    ...
    
    protected IQueryable<T> GetActive<T>(ObjectSet<T> entities)
        where T : class, IHideable
    {
      var allowedStates = new string[] { "Active" , "Pending" };    
    
      return (    
        from obj in entities
        where allowedStates.Contains(obj.State)
            && obj.Hidden == "No"
        select obj
      );
    }  
    
    0 讨论(0)
提交回复
热议问题