向Identity users表添加软删除

时间:2015-05-26 12:42:10

标签: c# entity-framework asp.net-mvc-5 asp.net-identity-2

我已将删除的列添加到我的Users表中,但显然注册Identity框架提供的新用户方法仍然会在数据库中看到这些用户,有没有办法告诉它忽略某个列?

注册

// this needs to ignore any DeletedAt where not null
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
    ...
}

登录

// this needs to ignore any DeletedAt where not null
result = await SignInManager.PasswordSignInAsync( user.UserName, model.Password, model.RememberMe, shouldLockout: true );

......还有任何其他外部登录信息需要告知该栏目。

1 个答案:

答案 0 :(得分:2)

signInManager内部覆盖SignInAsync方法,此方法用于每个登录进程(本地或外部)

public class ApplicationSignInManager : SignInManager<User, int>
{    

     public override async Task SignInAsync(User user, bool isPersistent, bool rememberBrowser)
     {
         if (!user.isDeleted)
         {
             await base.SignInAsync(user, isPersistent, rememberBrowser);
         } 
         else
         {
             ...
         }                      
     }
}

或创建自定义UserStore并覆盖GetUserAggregateAsync方法(在所有“查找”方法中调用):

public class CustomUserStore : UserStore<ApplicationUser>
{
    public CustomUserStore(ApplicationDbContext context) : base(context) { }

    protected override async Task<ApplicationUser> GetUserAggregateAsync(Expression<Func<ApplicationUser, bool>> filter)
    {
        var user = await base.GetUserAggregateAsync(filter);

        // if user is found but soft deleted then ignore and return null
        if (user != null && user.IsDeleted)
        {
            return null;
        }

        return user;
    }
}