当我尝试使用以下代码更新用户表时,它没有在相关的Filter表中创建新行,这是我在ApplicationUser类中创建的自定义对象。
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();
}
答案 0 :(得分:0)
解决方案是使用UserManager的内置功能,而不是尝试手动更新用户表。
示例:
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);