环境:使用ef6的vs2013 asp.net mvc5项目
当我通过调用UserManager.DeleteAsync(用户)删除用户时 表中的系统默认用户信息(" User")已删除,但用户配置文件表(" UserInfo")仍保留在数据库中。如何删除它? 有人可以帮忙吗?谢谢
这是我的代码:
public class AppUser : IdentityUser
{
....
public virtual UserInfo CustomInfo { get; set; }
}
public class UserInfo
{
[Key]
public int ID { get; set; }
public string FullName { get; set; }
...
public string OtherContacts { get; set; }
}
public class AppUserStore : UserStore<AppUser>
{
public AppUserStore(AccountDbContext context)
: base(context)
{
}
public override Task<AppUser> FindByIdAsync(string userId)
{
return Users.Include(u => u.CustomInfo).Include(u => u.Roles).Include(u => u.Claims).Include(u => u.Logins).FirstOrDefaultAsync(u => u.Id == userId);
}
public override Task<AppUser> FindByNameAsync(string userName)
{
return Users.Include(u => u.CustomInfo).Include(u => u.Roles).Include(u => u.Claims).Include(u => u.Logins).FirstOrDefaultAsync(u => u.UserName == userName);
}
}
public class AccountDbContext : IdentityDbContext<AppUser>
{
public AccountDbContext()
: base("CommonDbContext", throwIfV1Schema: false)
{
}
public static AccountDbContext Create()
{
return new AccountDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<AppUser>()
.ToTable("User")
.HasRequired(x => x.CustomInfo);
modelBuilder.Entity<UserInfo>().ToTable("UserInfo");
modelBuilder.Entity<IdentityRole>().ToTable("Role");
modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaim");
modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogin");
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRole");
}
public IDbSet<UserInfo> UserInfos { get; set; }
}
答案 0 :(得分:0)
1.在AccountDbContext中添加DbSet
public IDbSet<UserInfo> UserInfos { get; set; }
2.在AppUserStore中:
public override async Task DeleteAsync(AppUser user)
{
var context = Context as AccountDbContext;
context.UserInfos.Remove(user.CustomInfo);
context.Users.Remove(user);
await context.SaveChangesAsync();
}