这是表格

用户

UserId
UserName
Password
EmailAddress

还有代码..

public void ChangePassword(int userId, string password){
//code to update the password..
}

当前回答

虽然我已经晚了,但这就是我所做的,我花了一段时间去寻找一个让我满意的解决方法;当你通过“白名单”概念显式地定义它们是什么时,这只会为更改的字段生成一个UPDATE语句,这更安全,可以防止web表单注入。

摘自我的ISession数据存储库:

public bool Update<T>(T item, params string[] changedPropertyNames) where T 
  : class, new()
{
    _context.Set<T>().Attach(item);
    foreach (var propertyName in changedPropertyNames)
    {
        // If we can't find the property, this line wil throw an exception, 
        //which is good as we want to know about it
        _context.Entry(item).Property(propertyName).IsModified = true;
    }
    return true;
}

如果您愿意,可以将其封装在try. catch中,但我个人希望调用者了解此场景中的例外情况。

它将以类似这样的方式被调用(对我来说,这是通过ASP。NET Web API):

if (!session.Update(franchiseViewModel.Franchise, new[]
    {
      "Name",
      "StartDate"
  }))
  throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));

其他回答

结合几项建议,我提出如下:

    async Task<bool> UpdateDbEntryAsync<T>(T entity, params Expression<Func<T, object>>[] properties) where T : class
    {
        try
        {
            var entry = db.Entry(entity);
            db.Set<T>().Attach(entity);
            foreach (var property in properties)
                entry.Property(property).IsModified = true;
            await db.SaveChangesAsync();
            return true;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("UpdateDbEntryAsync exception: " + ex.Message);
            return false;
        } 
    }

UpdateDbEntryAsync(dbc, d => d.Property1);//, d => d.Property2, d => d.Property3, etc. etc.);

或通过

await UpdateDbEntryAsync(dbc, d => d.Property1);

或通过

bool b = UpdateDbEntryAsync(dbc, d => d.Property1).Result;

实体框架跟踪您通过DbContext从数据库查询的对象的更改。例如,如果你的DbContext实例名是DbContext

public void ChangePassword(int userId, string password){
     var user = dbContext.Users.FirstOrDefault(u=>u.UserId == userId);
     user.password = password;
     dbContext.SaveChanges();
}

我使用valueinjector nuget注入绑定模型到数据库实体使用如下:

public async Task<IHttpActionResult> Add(CustomBindingModel model)
{
   var entity= await db.MyEntities.FindAsync(model.Id);
   if (entity== null) return NotFound();

   entity.InjectFrom<NoNullsInjection>(model);

   await db.SaveChangesAsync();
   return Ok();
}

注意使用自定义约定,如果属性在服务器上为空,则不更新属性。

ValueInjecter v3 +

public class NoNullsInjection : LoopInjection
{
    protected override void SetValue(object source, object target, PropertyInfo sp, PropertyInfo tp)
    {
        if (sp.GetValue(source) == null) return;
        base.SetValue(source, target, sp, tp);
    }
}

用法:

target.InjectFrom<NoNullsInjection>(source);

值注入器V2

查找这个答案

警告

您将不知道该属性是被故意清除为null还是它只是没有任何值。换句话说,属性值只能被替换为另一个值,而不能被清除。

在实体框架核心中,Attach返回条目,所以你所需要的是:

var user = new User { Id = userId, Password = password };
db.Users.Attach(user).Property(x => x.Password).IsModified = true;
db.SaveChanges();

虽然我已经晚了,但这就是我所做的,我花了一段时间去寻找一个让我满意的解决方法;当你通过“白名单”概念显式地定义它们是什么时,这只会为更改的字段生成一个UPDATE语句,这更安全,可以防止web表单注入。

摘自我的ISession数据存储库:

public bool Update<T>(T item, params string[] changedPropertyNames) where T 
  : class, new()
{
    _context.Set<T>().Attach(item);
    foreach (var propertyName in changedPropertyNames)
    {
        // If we can't find the property, this line wil throw an exception, 
        //which is good as we want to know about it
        _context.Entry(item).Property(propertyName).IsModified = true;
    }
    return true;
}

如果您愿意,可以将其封装在try. catch中,但我个人希望调用者了解此场景中的例外情况。

它将以类似这样的方式被调用(对我来说,这是通过ASP。NET Web API):

if (!session.Update(franchiseViewModel.Franchise, new[]
    {
      "Name",
      "StartDate"
  }))
  throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));