小编Sta*_*nko的帖子

ExecuteUpdateAsync 的 linq 表达式

我怀着极大的热情在 EF Core 7 中发现了 ExecuteDeleteAsync 和 ExecuteUpdateAsync。它们有助于使我的代码变得更简单、更快。无需使用自制程序批量删除或更新1-2个字段。无论如何,我遇到过应该在运行时选择要更新的数据库的确切表和字段的情况。

我可以使用数据库表:

public static IQueryable<object> Set(this DbContext context, Type entity) =>
        context.ClrQuery(context.ClrType(entity));
Run Code Online (Sandbox Code Playgroud)

我有制作表达式来过滤行的方法:

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);
}
Run Code Online (Sandbox Code Playgroud)

所以我可以找到要更新的行

IQueryable Source = …
Run Code Online (Sandbox Code Playgroud)

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

2
推荐指数
1
解决办法
4705
查看次数