Linq Entity Framework generic filter method

ⅰ亾dé卋堺 提交于 2019-12-18 07:03:35

问题


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

Example #1:

protected IQueryable<Database.Product> GetActiveProducts( ObjectSet<Database.Product> products ) {

    var allowedStates = new string[] { "Active" , "Pending" };

    return (
        from product in products
        where allowedStates.Contains( product.State )
            && product.Hidden == "No"
        select product
    );

}

Example #2:

protected IQueryable<Database.Customer> GetActiveProducts( ObjectSet<Database.Customer> customers ) {

    var allowedStates = new string[] { "Active" , "Pending" };

    return (
        from customer in customers
        where allowedStates.Contains( customer.State )
            && customer.Hidden == "No"
        select customer
    );

}

As you can see, these methods are identical apart from the Entity types they operate on. I have more than 10 of these types of methods, one for each type of Entity in my system.

I am trying to understand how I could have 1 single method for which I could pass in any Entity type, and have it perform the where clause if the 2 fields/properties exist.

I do not use Inheritance in the database, so as far as the system goes, it is coincidental that each of the Entity types have the fields "Hidden" and "State".

My Googling tells me it has something to do with building code using Expression.Call() but my head is now spinning!


回答1:


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



回答2:


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 :)



来源:https://stackoverflow.com/questions/3220155/linq-entity-framework-generic-filter-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!