开发者

How to apply global filter on Entity Framework?

开发者 https://www.devze.com 2022-12-27 03:35 出处:网络
I have a table in my model named Customers with a field IsActive开发者_Go百科. Whenever I run a query on Customers, only the active customers should be retrieved. I can include the filter in every que

I have a table in my model named Customers with a field IsActive开发者_Go百科. 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


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.

How to apply global filter on Entity Framework?


Maybe you could declare new property and use it:

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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消