MongoDB學(xue)習(xi)筆記~為IMongoRepository接口更新指定字段
對于MongoDB來說,它的(de)更(geng)新(xin)(xin)(xin)建議是(shi)對指定字段來說的(de),即不是(shi)把(ba)對象里(li)的(de)所有字段都進行update,而是(shi)按需去(qu)(qu)更(geng)新(xin)(xin)(xin),這在(zai)性(xing)(xing)(xing)能上(shang)是(shi)最(zui)優的(de),這當然(ran)也是(shi)非常容(rong)易理解(jie)(jie)的(de),我(wo)們今天(tian)要(yao)實現的(de)就是(shi)這種按需去(qu)(qu)更(geng)新(xin)(xin)(xin),并(bing)且(qie),我(wo)還是(shi)不希望將(jiang)MongoDB的(de)內核(he)暴露出(chu)去(qu)(qu),這時,我(wo)想到(dao)了(le)EF時候的(de)按需要(yao)更(geng)新(xin)(xin)(xin),即為(wei)實體哪些(xie)屬性(xing)(xing)(xing)賦值(zhi)就更(geng)新(xin)(xin)(xin)哪些(xie)屬性(xing)(xing)(xing);這個(ge)功能實際上(shang)使用了(le)表達(da)式樹(shu),將(jiang)你的(de)屬性(xing)(xing)(xing)和屬性(xing)(xing)(xing)值(zhi)存(cun)儲到(dao)Expression里(li),然(ran)后在(zai)update方(fang)法內部再進行解(jie)(jie)析即可,具體代碼如下(xia)
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)//更新集中不能有實體(ti)鍵_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))); }
其實在(zai)方法調用上(shang)也是(shi)非常容易(yi)的,我們來(lai)看(kan)這個例(li)子
[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(); }
通過上面代(dai)碼我們可以看到,只是將需要更(geng)新(xin)的(de)字段(duan)進(jin)行賦值即可!