Created
October 12, 2012 06:21
-
-
Save jiangzhuo/3877606 to your computer and use it in GitHub Desktop.
mongodb repository inc operation using offical mongodb Driver, using Linq Expression Extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void Inc(Expression<Func<T, bool>> predicate, Expression<Func<T, T>> updateExpression) | |
{ | |
var propertyNamesAndValues = new Dictionary<string, int>(); | |
var query = ((MongoQueryable<T>)this.collection.AsQueryable<T>().Where(predicate)).GetMongoQuery(); | |
var memberInitExpression = (MemberInitExpression)updateExpression.Body; | |
if (memberInitExpression == null) | |
throw new ArgumentException("The update expression must be of type MemberInitExpression.", "updateExpression"); | |
foreach (MemberBinding binding in memberInitExpression.Bindings) | |
{ | |
var memberAssignment = binding as MemberAssignment; | |
if (memberAssignment == null) | |
throw new ArgumentException("The update expression MemberBinding must only by type MemberAssignment.", "updateExpression"); | |
Expression memberExpression = memberAssignment.Expression; | |
ParameterExpression parameterExpression = null; | |
memberExpression.Visit((ParameterExpression p) => | |
{ | |
parameterExpression = p; | |
return p; | |
}); | |
if (parameterExpression == null) | |
{ | |
object value; | |
if (memberExpression.NodeType == ExpressionType.Constant) | |
{ | |
var constantExpression = memberExpression as ConstantExpression; | |
if (constantExpression == null) | |
throw new ArgumentException( | |
"The MemberAssignment expression is not a ConstantExpression.", "updateExpression"); | |
value = constantExpression.Value; | |
} | |
else | |
{ | |
LambdaExpression lambda = Expression.Lambda(memberExpression, null); | |
value = lambda.Compile().DynamicInvoke(); | |
} | |
if (value != null) | |
{ | |
propertyNamesAndValues.Add(binding.Member.Name, Convert.ToInt32(value)); | |
} | |
else | |
{ | |
propertyNamesAndValues.Add(binding.Member.Name, Convert.ToInt32(value)); | |
} | |
} | |
} | |
var update = new UpdateBuilder(); | |
foreach (var kv in propertyNamesAndValues) | |
{ | |
update.Inc(kv.Key, kv.Value); | |
} | |
this.collection.Update(query, update); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment