Sudheep
Sudheep

Reputation: 32

Update only a single column using EF5 in MVC4

I have an UserProfile model

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; }
}

I want to update only the password field. This is the code I am trying

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;
                        }                     

                    }                   
                }

I get the DbEntityValidationException on the required fields. Please guide me in solving this.

Regards Sudheep

Upvotes: 0

Views: 1157

Answers (1)

GMan
GMan

Reputation: 464

I usually would do a

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

then set

myEntity.Password = "new password";

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

/* why do you have it as unchanged? */

jdc.saveChanges()

Upvotes: 1

Related Questions