DevWithSigns
DevWithSigns

Reputation: 725

Cannot update single property in Entity Framework

I'm trying to update only single property of an entity but I cannot update it.

Here is what I have done so far:

public async Task ChangePassword(string User, string Password)
{
    using (var context = new abcContext())
    {
        var user = await context.Members.Where(c => c.UserName == User).FirstOrDefaultAsync();
        var member = context.Members.Find(user.PersonID);
        var coolBlog = new Member { PersonID = member.PersonID, 
                                    Password = member.Password };

        context.Configuration.ValidateOnSaveEnabled = false;

        context.Members.Attach(member);
        context.Entry(member).Property(c => c.Password).OriginalValue = coolBlog.Password.ToString();
        context.Entry(member).Property(m => m.Password).IsModified = true;

        await context.SaveChangesAsync();
    };               
}

It is not updating password property in my database. Please guide me I have searched internet but couldn't find any appropriate solution.

Upvotes: 0

Views: 141

Answers (1)

Fanda
Fanda

Reputation: 3786

You probably want this:

public async Task ChangePassword(string User, string Password)
{
    using (var context = new abcContext())
    {
        var user = await context.Members.Where(c => c.UserName == User).FirstOrDefaultAsync();
        if (user != null)
        {
            user.Password = Password; // do some hashing on password to not store plain password
            await context.SaveChangesAsync();
        }             
    }
}

Upvotes: 2

Related Questions