linq expression for ExecuteUpdateAsync
07:29 17 Nov 2022

I have found ExecuteDeleteAsync and ExecuteUpdateAsync in EF Core 7 with great enthusiasm. They help to make my code much simpler and faster. There is no need to use self-made procedures for batch delete or update of 1-2 fields. Anyway I have situations when the exact table and field of database for update should be selected in run time.

I can use the database table:

public static IQueryable Set(this DbContext context, Type entity) =>
        context.ClrQuery(context.ClrType(entity));

I have the method to make expression to filter rows:

public static IQueryable Where(this IQueryable source, string equalProperty, object value, [NotNull] Type EntityType)
{
    PropertyInfo? property = EntityType.GetProperty(equalProperty);
    if (property == null)
        throw new NotImplementedException($"Type {EntityType.Name} does not contain property {equalProperty}");

    ParameterExpression parameter = Expression.Parameter(EntityType, "r");
    MemberExpression member = Expression.MakeMemberAccess(parameter, property);
    LambdaExpression whereExpression = Expression.Lambda(Expression.Equal(member, Expression.Constant(value, property.PropertyType)), parameter);
    MethodCallExpression resultExpression = WhereCall(source, whereExpression);
    return source.Provider.CreateQuery(resultExpression);
}

So I can find the rows to make update using

IQueryable Source = db.Set(EntityType).Where(FieldName, FieldValue, EntityType);
            

I should make expression to update IQueryable ExecuteUpdateQuery = Source.ExecuteUpdateAsync(EntityType, FieldName, FieldValue);

What is the way to access to expression for SetProperty?

linq entity-framework-core expression-trees c#-11.0 ef-core-7.0