2013-05-07 12 views
0

EF5我有一个用户配置模型更新只有一个字段使用MVC4

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

EF只会更新更改的列。使用sql分析器来确认它。 – 2013-05-07 10:17:37

回答

1

我通常会做一个

var myEntity = jdc.(tableName).find(userID); 

然后设置

myEntity.Password = "new password"; 

jdc.Entry(userProfile).State = System.Data.EntityState.Modified; 

/ *你为什么把它作为不变? * /

jdc.saveChanges() 
+0

但这样你执行2个sql查询,对吧? (一个用于查找,另一个用于更新)。有一种方法来执行此更新只有一个查询? – 2013-11-02 03:34:05

相关问题