我有一个UserProfile模型
public class UserProfile
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Key]
[Required]
public string EmailAddress { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Surname { get; set; }
[Required]
public string BusinessUnit { get; set; }
[Required]
public string JobRole { get; set; }
public bool IsEnabled { get; set; }
public string Password { get; set; }
}
我想只更新密码字段。 这是我正在尝试的代码
if (ModelState.IsValid)
{
var context = new JhaDbContext();
using (JhaDbContext jdc = new JhaDbContext())
{
try
{
jdc.UserProfiles.Attach(userProfile);
userProfile.Password = model.NewPassword;
jdc.SaveChanges();
httpStatus = HttpStatusCode.OK;
}
catch (InvalidOperationException ioe)
{
httpStatus = HttpStatusCode.BadRequest;
}
catch (DbEntityValidationException ev)
{
httpStatus = HttpStatusCode.BadRequest;
}
}
}
我在必填字段上获得了DbEntityValidationException。请指导我解决这个问题。
此致 Sudheep
答案 0 :(得分:1)
我通常会做一个
var myEntity = jdc.(tableName).find(userID);
然后设置
myEntity.Password = "new password";
jdc.Entry(userProfile).State = System.Data.EntityState.Modified;
/ *为什么你没有改变它? * /
jdc.saveChanges()