您的位置:首页 > 数据库 > Mongodb

MongoDB学习笔记~为IMongoRepository接口更新指定字段

2015-04-30 22:22 477 查看
回到目录

对于MongoDB来说,它的更新建议是对指定字段来说的,即不是把对象里的所有字段都进行update,而是按需去更新,这在性能上是最优的,这当然也是非常容易理解的,我们今天要实现的就是这种按需去更新,并且,我还是不希望将MongoDB的内核暴露出去,这时,我想到了EF时候的按需要更新,即为实体哪些属性赋值就更新哪些属性;这个功能实际上使用了表达式树,将你的属性和属性值存储到Expression里,然后在update方法内部再进行解析即可,具体代码如下

public void Update<T>(System.Linq.Expressions.Expression<Action<T>> entity) where T : class
{
var query = new QueryDocument();
var fieldList = new List<UpdateDefinition<TEntity>>();

var param = entity.Body as MemberInitExpression;
foreach (var item in param.Bindings)
{
string propertyName = item.Member.Name;
object propertyValue;
var memberAssignment = item as MemberAssignment;
if (memberAssignment.Expression.NodeType == ExpressionType.Constant)
{
propertyValue = (memberAssignment.Expression as ConstantExpression).Value;
}
else
{
propertyValue = Expression.Lambda(memberAssignment.Expression, null).Compile().DynamicInvoke();
}

if (propertyName != EntityKey)//更新集中不能有实体键_id
{
fieldList.Add(Builders<TEntity>.Update.Set(propertyName, propertyValue));
}
else
{
query = new QueryDocument("_id",new ObjectId(propertyValue.ToString()));
}

}

ForWait(() => _table.UpdateOneAsync(query, Builders<TEntity>.Update.Combine(fieldList)));
}


其实在方法调用上也是非常容易的,我们来看这个例子

[HttpPost]
public ActionResult Edit(WebManageUsers entity)
{
if (ModelState.IsValid)
{
_webManageUsersRepository.Update<WebManageUsers>(i => new WebManageUsers
{
Id = entity.Id,
LoginName = entity.LoginName
});
return RedirectToAction("Index");
}
ModelState.AddModelError("", "请认真填写表单!");
return View();
}


通过上面代码我们可以看到,只是将需要更新的字段进行赋值即可!

回到目录
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: