making a global filter for entity framework

前端 未结 2 1324
星月不相逢
星月不相逢 2020-12-10 06:08

For my models I have a active attribute on all of them, and i want to filter all inactive if the model was not displayed on the administration What is the best

2条回答
  •  长情又很酷
    2020-12-10 06:45

    You can create extension methods like

    public static IQueryable Where(this IQueryable source, Expression> predicate)
    {
        source = source.Where("isActive == true"); // From System.linq.Dynamic Library
        source = Queryable.Where(source, predicate);
        return source;
    }
    

    and use them like

    var user = db.UserProfiles.Include("webpages_Roles").Where(u => u.UserId < 30);
    

    This should work, Please Let me know if you need more information.

    Note : Please Add Nuget package for System.Linq.Dynamic to have dynamic Linq Library

    Update 1:

    I have included IsActive in webpages_Roles and UsreProfile table of simple membership and also included one more table Role Priority which refers to webpages_Roles, for easy to use I have changed the all the relation ships to one to many(from many to many). now if I use code similar to yours, extension method gives error when there is any user for which there are no roles.

    If I give roles to every user and I have priority for every roles then this won't give error.

    Please Let me know if you still need any other info.

    Update 2

    You can create one extension Method like

    public static IQueryable WhereActive(this IQueryable source)
            {
                return source.Where("isActive == true"); // From System.linq.Dynamic Library
            }
    

    and call other methods like

    var user = db.UserProfiles.Include("webpages_Roles").WhereActive().Where(u => u.UserId < 30);
    

    or

    var user = db.UserProfiles.Include("webpages_Roles").WhereActive().FirstOrDefault(u => u.UserId < 30);
    

    Please Let me know if you still need any other info.

提交回复
热议问题