making a global filter for entity framework

前端 未结 2 1313
星月不相逢
星月不相逢 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<T> Where<T>(this IQueryable<T> source, Expression<Func<T, bool>> predicate)
    {
        source = source.Where("isActive == true"); // From System.linq.Dynamic Library
        source = Queryable.Where<T>(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<T> WhereActive<T>(this IQueryable<T> 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.

    0 讨论(0)
  • 2020-12-10 06:54

    You can do it like this:

    1. In OnModelCreating add an IsDeleted discriminator to every entity that can be soft deleted
    2. Override SaveChanges and find all the entries to be deleted
    3. Run SQL on these entries to set the IsDeleted discriminator then set their state to "detached"
    4. Change any unique indexes to ignore any soft deleted records

    You can find working code at this answer: How to soft delete using Entity Framework Code First

    0 讨论(0)
提交回复
热议问题