Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
849 views
in Technique[技术] by (71.8m points)

c# - Linq Entity Framework generic filter method

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...