【问题标题】:In ASP.NET MVC, How to Update Current User Info?在 ASP.NET MVC 中,如何更新当前用户信息?
【发布时间】:2015-04-07 05:28:23
【问题描述】:

当您为额外的用户信息(例如名字和出生日期)添加额外的表格时,您如何在控制器中更新或编辑这些信息? 这是我自定义的身份用户模型:

public class ApplicationUser : IdentityUser
{
   public virtual UserEntity UserEntity { get; set;}

   public class UserInfo
   {
     // additional user properties in another table
     public int Id { get; set; }
     public string FirstName { get; set; }
     public DateTime BirthDate {get; set; }
     public virtual ApplicationUser User { get; set; }
   }
}

此模型表示一个 UserInfo 仅属于一个用户。简而言之,关系是 1:0/1(一到零或 1)

要向用户更新或添加更多信息,我想在控制器中应该有点像这样,但事实并非如此:

public class AccountManager : Controller
{
   [HttpPost]
   public ActionResult UpdateUserInfo(string first_name, DateTime birth_date)
   {
      string currentUserId = User.Identity.GetUserId();
      var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
      var currentUser = userManager.FindById(currentUserId);

      currentUser.UserInfo.FirstName = first_name;
      currentUser.UserInfo.BirthDate = birth_date;

      currentUser.SaveChanges();

      // some codes removed for clarity
   }
}

我希望很清楚。您如何更新身份用户的相关模型? 另请注意,用户仍然没有现有的 UserInfo 记录(关系仍然是 1:0)。

【问题讨论】:

    标签: asp.net-mvc entity-framework relational-database customization asp.net-identity


    【解决方案1】:

    当你从 db 获取数据时,Savechanges 更新

    如果你想更新你应该使用

    currentUser.Entry(first_name).State = System.Data.EntityState.Modified;
    

    或者你可以使用

    currentUser.Entry(existing first_name).CurrentValues.SetValues(first_name);
    

    【讨论】:

    • 我在这里看到的唯一问题是currentUser 不是上下文。我认为应该是userManager.Entry(currentUser).State = EntityState.Modified; 虽然我不确定。我之前没有看到像在 OP 中那样声明上下文。
    • 嘿@Khan .. 不是原创海报...只是一个偶然的支持者;)
    • 我不是这个问题的原始发帖人。我赞成您的回答,因为它看起来正确。为链接拍摄。 1 班轮上下文有点令人困惑。
    • 谢谢,我试过了,但它给我带来了这个错误:附加类型为“my_project.Models.ApplicationUser”的实体失败,因为另一个相同类型的实体已经具有相同的主键值。使用 ... 时可能会发生这种情况
    • 我会推荐你​​阅读这篇文章,它可能会有所帮助stackoverflow.com/questions/20444022/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    相关资源
    最近更新 更多