开发者

Entity Framework Query Filter

开发者 https://www.devze.com 2023-03-31 13:46 出处:网络
Is it possible to add a sort-of a global filter to an Entity Framework object context? Such as having an ObjectMaterialized which can return an indicator of whether or not to include a given obje开发者

Is it possible to add a sort-of a global filter to an Entity Framework object context? Such as having an ObjectMaterialized which can return an indicator of whether or not to include a given obje开发者_如何学Cct in the result set.


No it is not possible. Entity framework and its built in providers don't have any support for global filters.

You can achieve some basic filtering with simple wrapper:

public class MyContext : ObjectContext
{
    private ObjectSet<MyEntity> myEntities;

    public Expression<Func<MyEntity, bool>> GlobalMyEntityFilter { get; set; }

    public IQueryable<MyEntity> MyEntities
    {
        get
        {
            if (GlobalMyEntityFilter != null)
            {
                return myEntities.Where(GlobalMyEntityFilter);
            }

            return myEntities;
        }
    }  
}


Are you trying to do something like only show the active Customers? If so, you can use Inheritance and create an ActiveCustomer type and add a condition in your mapping to Status == "Active". Then set your Customer type as an Abstract Base Class to prevent direct instantiation. You can then query your model for Customers.OfType<ActiveCustomer>().

0

精彩评论

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