Hernan
Hernan

Reputation: 503

How to apply global filter on Entity Framework?

I have a table in my model named Customers with a field IsActive. Whenever I run a query on Customers, only the active customers should be retrieved. I can include the filter in every query, but that doesn't look very. I would like to be able to override the Customers property at the Object Context lever, but I am not sure if this is possible. Any help would be very appreciated! Thanks

Upvotes: 4

Views: 2541

Answers (4)

Levelbit
Levelbit

Reputation: 170

I don't know why this is problem for you. You can put one query inside some function:

IEnumerable<Customers> GetActiveCustomers()  
{  
    var activeCustomers =   
    from cust in db.Customers  
    where cust.IsActive == true  
    select cust;  
    return activeCustomers;  
}

And call it every time you like. You can even put active customers in some private List or even better ObservableCollection. Then you can query your result again:

 var myCustomers =  
 from cust in GetActiveCustomers()  
 where cust.CustomerName == "John"  
 select cust;  

and that's it.

Upvotes: 0

muruge
muruge

Reputation: 4133

Although a late response, I will put it here so it can help others.

You can also set a condition for your entity in your edmx file. Select your entity and Goto Mapping Details and create a new condition.

enter image description here

Upvotes: 5

LukLed
LukLed

Reputation: 31862

Maybe you could declare new property and use it:

public partial class MyEntities
{
    public ObjectQuery<User> ActiveCustomers
    {
        get
        {
            return Customers.Where(c => c.IsActive);
        }
    }
}

Upvotes: 3

Laurence Burke
Laurence Burke

Reputation: 2358

All you need to do is retrieve all of the customers no matter if they are active or not and then use a

foreach(Customer c in Results)
{
if(c.IsActive)
   listofactivecustomers.Add(c);
}

Upvotes: -5

Related Questions