当您为其他用户信息(例如名字和生日)添加其他表时,如何在控制器中更新或编辑这些信息? 这是我自定义的身份用户模型:
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
}
}
我希望它清楚。您如何更新Identity User的相关模型? 另请注意,用户仍然没有现有的UserInfo记录(关系仍为1:0)。
答案 0 :(得分:3)
从db
获取数据时保存更改更新如果您想要更新,请使用
currentUser.Entry(first_name).State = System.Data.EntityState.Modified;
或者您可以使用
currentUser.Entry(existing first_name).CurrentValues.SetValues(first_name);