3

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

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(其一是0或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)。

回答

3

的SaveChanges更新,当你从数据库

,如果你想更新你应该使用

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

,或者您可以使用

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

我在这里看到的唯一的问题数据是' currentUser'不是上下文。我认为它应该可能是'userManager.Entry(currentUser).State = EntityState.Modified;'虽然我不确定。我还没有看到正如OP之前所宣称的那样。 – 2015-04-07 07:25:04

+0

嘿@Khan ..不是原创海报...只是一个随便upvoter;) – 2015-04-07 07:28:22

+0

我不是这个问题的原始海报。我赞成你的答案,因为它看起来是正确的。虽然拍摄了链接。 1班轮上下文有点混乱。 – 2015-04-07 07:46:53