如何更新 ApplicationUser 实体及其自定义属性和子对象?

How can I update ApplicationUser entity and also its custom properties and child objects?

当我尝试使用以下代码更新用户 table 时,它没有在相关过滤器 table 中创建新行,这是我在 ApplicationUser class.

 using (var dbContext = new ApplicationDbContext())
        {
            var user = dbContext.Users.Where(u=> u.Id == model.Id)
            if (user.Filter == null)
                 user.Filter = new FilterPal();
            user.Filter.IsFilterOn = model.IsFilterOn;
            dbContext.SaveChanges();
        }

解决方案是使用 UserManager 的内置函数,而不是尝试手动更新用户 table。

示例:

    private ApplicationUserManager _userManager;
    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }
    var user = UserManager.FindById(User.Identity.GetUserId());
    if (user.Filter == null)
        user.Filter = new FilterPal();
    user.Filter.IsFilterOn = model.IsFilterOn;
    UserManager.Update(user);

编辑:

用这个就够了属性:

    private ApplicationUserManager _userManager
    {
        get
        {
            return HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
    }
    var user = _userManager.FindById(User.Identity.GetUserId());
    if (user.Filter == null)
        user.Filter = new FilterPal();
    user.Filter.IsFilterOn = model.IsFilterOn;
    _userManager.Update(user);