I have the following function which is actually a wrapper around Z.EntityFramework.Plus bulk update:
public static int UpdateBulk<T>(this IQueryable<T> query, Expression<Func<T, T>> updateFactory) where T : IBaseEntity, new()
{
Expression<Func<T, T>> modifiedExpression = x => new T() { ModifiedBy = "Test", ModifiedDate = DateTime.Now };
var combine = Expression.Lambda<Func<T, T>>(
Expression.AndAlso(
Expression.Invoke(updateFactory, updateFactory.Parameters),
Expression.Invoke(modifiedExpression, modifiedExpression.Parameters)
),
updateFactory.Parameters.Concat(modifiedExpression.Parameters)
); //This returns an error
return query.Update(combine);
}
Called like this:
decimal probId = ProbId.ParseDecimal();
db.Problems
.Where(e => e.ProbId == probId)
.UpdateBulk(e => new Problem() {
CatId = Category.ParseNullableInt(),
SubCatId = SubCategory.ParseNullableInt(),
ListId = Problem.ParseNullableInt()
});
Where IBaseEntity is defined as follows:
public abstract class IBaseEntity
{
public System.DateTime CreatedDate { get; set; }
public string CreatedBy { get; set; }
public System.DateTime ModifiedDate { get; set; }
public string ModifiedBy { get; set; }
public string DeletedBy { get; set; }
}
The 'Problem' class by the way implements IBaseEntity.
What I want to do is automatically append ModifiedBy and ModifiedDate to updateFactory in the UpdateBulk function so that this doesn't have to be done in every call to UpdateBulk.
I tried in the above UpdateBulk function to combine the parsed 'updateFactory' expression with the 'modifiedExpression' but it returns the error:
the binary operator AndAlso is not defined for the types 'Problem'
Is it possible to merge Expression like this and if so, what am I doing wrong? If not, how can I merge ModifiedBy = "Test", ModifiedDate = DateTime.Now into the updateFactory expression?
Thanks, Rod
.Where(e => e.ProbId == probId)
to.Where(e=> e.ProbId == null ? (e.ProbId == probId) : false)
? Sometimes this problem is caused by null data returned. – CatieAndAlso
is for theExpression<Func<T,bool>>
, forExpression<Func<T,T>>
, you need a Expression Visitor defined here – Romans