回到目錄
對于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();
}
通過上面代碼我們可以看到,隻是将需要更新的字段進行指派即可!
作者:倉儲大叔,張占嶺,
榮譽:微軟MVP
QQ:853066980
支付寶掃一掃,為大叔打賞!
