无法更新Entity Framework中的单个属性

时间:2014-06-28 03:42:40

标签: asp.net-mvc entity-framework asp.net-mvc-4 asp.net-mvc-5 entity-framework-6

我试图仅更新实体的单个属性,但我无法更新它。

这是我到目前为止所做的:

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

我的数据库中没有更新密码属性。请指导我,我已经搜索过互联网,但无法找到合适的解决方案。

1 个答案:

答案 0 :(得分:2)

你可能想要这个:

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