我有一个ASP.NET应用程序,其中用户使用UserIdentity
类进行身份验证。最近,我刚刚通过在ApplicationUser
类中添加'ActiveStatus'来实现了一个软删除功能。
问题出现在用户无法将软删除的电子邮件地址重新注册为新帐户的情况下。有人可以帮我弄这个吗?
我刚刚使用2015年8月28日由Rakesh Babu Paruchuri发布的https://www.codeguru.com/csharp/csharp/soft-deleting-entities-cleanly-using-entity-framework-6-interceptors.html的说明和示例代码,在我的MVC应用程序中实现了这一目标。
该博客条目的示例代码链接是https://github.com/rakeshbabuparuchuri/EFExpensionPoints
如果这些链接不可用,这里的关键点是:
它使用自定义属性“SoftDeleteAttribute”和Entity Framework Interceptor。我在自己的项目中包含的关键元素是:
然后你注册拦截器 - 在我的例子中,我将以下代码放在与我的ApplicationDbContext相同的文件中(继承自IdentityDbContext):
public class ApplicationDbConfiguration : DbConfiguration
{
public ApplicationDbConfiguration()
{
AddInterceptor(new Helpers.SoftDeleteInterceptor());
}
}
并重写OnModelCreating以添加处理SoftDeleteAttribute的约定:
var conv = new AttributeToTableAnnotationConvention<SoftDeleteAttribute, string>(
"SoftDeleteColumnName",
(type, attributes) => attributes.Single().ColumnName);
modelBuilder.Conventions.Add(conv);
最后一步是将SoftDeleteAttribute添加到我的ApplicationUser类。
[SoftDelete("IsDeleted")]
public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
//some code removed to emphasise the important bit
[StringLength(150)]
public string Forenames { get; set; }
[StringLength(50)]
public string Surname { get; set; }
public bool IsDeleted { get; set; }
}
除此之外,我还删除并重新创建了数据库中users表的Username列的唯一索引,以便它使用条件以便我可以重用已删除用户的用户名(不推荐但是我使用现有数据库:
CREATE UNIQUE NONCLUSTERED INDEX [UserNameIndex]
ON [dbo].[tbl_user] ([UserName] ASC)
WHERE ([IsDeleted]=(0))
我也进行了一些迁移 - 我不确定迁移步骤是否对于它的运行非常重要,我实际上今天只是自己做了这个,所以没有机会针对手动创建的数据库进行尝试。
通过这些更改,我可以软删除用户,然后使用相同的用户名和/或电子邮件地址创建新用户
我还在http://marisks.net/2016/02/27/entity-framework-soft-delete-and-automatic-created-modified-dates/上找到了一个类似的解决方案,它也使用了命令拦截器,但是用固定的列名替换了SoftDelete属性,并且代码排列有点不同。他还包括更新Created和Modified列以及软删除标志。那篇文章引用了Rakesh的文章,它帮我找到了:)