Linq Entity Framework Common Filter Method

I have several methods that perform a standard filter on data from my objects (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, except for the types of objects on which they work. I have over 10 of these types of methods, one for each Entity type in my system.

I'm trying to figure out how I could have one single method for which I could pass any type of Entity, and get it to execute the where clause if there are 2 fields / properties.

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

My Googling , - Expression.Call(), !

+3
2

, - , . EF , - :

, (. Mark)

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

IQueryable<T> .

: " ... LINQ to Entities Entity Data Model".

, . IQueryable<T> , , .

, . :)

+3

Source: https://habr.com/ru/post/1754029/


All Articles