【发布时间】:2022-12-22 23:09:50
【问题描述】:
我以极大的热情在 EF Core 7 中找到了 ExecuteDeleteAsync 和 ExecuteUpdateAsync。它们有助于使我的代码更加简单和快速。批量删除或更新1-2个字段无需使用自制程序。 无论如何,在运行时应该选择要更新的确切表和数据库字段的情况。
我可以使用数据库表:
public static IQueryable<object> Set(this DbContext context, Type entity) =>
context.ClrQuery(context.ClrType(entity));
我有使表达式过滤行的方法:
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);
}
所以我可以找到要使用的行进行更新
IQueryable Source = db.Set(EntityType).Where(FieldName, FieldValue, EntityType);
我应该表达更新IQueryable ExecuteUpdateQuery = Source.ExecuteUpdateAsync(EntityType, FieldName, FieldValue);
SetProperty 表达式的访问方式是什么?
【问题讨论】:
-
ExecuteUpdateAsync 的返回值应该是 Task<int>,而不是 IQueryable
标签: linq entity-framework-core expression-trees c#-11.0 ef-core-7.0