You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何将字符串值作为属性名实现EF Core动态查询

问题根源

你代码里写的r => r.booleanName == true是编译期就固定成员访问逻辑的lambda表达式,EF Core会直接去找GuestModel上名为booleanName的属性,根本不会读取你同名字符串变量里存储的实际属性名——C#的静态成员访问不会在运行时解析字符串变量的内容,这就是你拿不到对应属性值的核心原因。

方案1:固定属性映射(最推荐,无注入风险)

你提到用户能选的总共就8个固定布尔属性,完全没必要搞复杂的动态逻辑,直接做参数和筛选表达式的映射即可,从根源上避免非法参数传入,性能也最好:

// 入参合法性校验
if (string.IsNullOrWhiteSpace(booleanName))
    throw new ArgumentException("筛选属性名不能为空");

// 配置所有允许用户选择的属性映射,替换成你自己实体的实际属性即可
var validFilters = new Dictionary<string, Expression<Func<GuestModel, bool>>>
{
    ["IsVip"] = g => g.IsVip,
    ["HasMedicalHistory"] = g => g.HasMedicalHistory,
    ["IsFirstVisit"] = g => g.IsFirstVisit,
    ["NeedFollowUp"] = g => g.NeedFollowUp,
    // 剩余4个属性按相同格式补充
};

if (!validFilters.TryGetValue(booleanName, out var filter))
    throw new ArgumentException("传入的筛选属性不合法");

// 直接传入表达式就能正常生成SQL查询
var test = await _context.GuestModel
    .Include(r => r.PatientModel)
    .OrderByDescending(r => r.GuestLastName)
    .Where(filter)
    .ToListAsync();
return test;
方案2:动态表达式构建(适合属性后续会扩展的场景)

如果后续可选属性会动态增减,不想维护映射表,可以手动构造EF Core能识别的表达式树,运行时生成对应筛选逻辑:

using System.Linq.Expressions;

var entityType = typeof(GuestModel);
var targetProp = entityType.GetProperty(booleanName);
// 必须校验属性存在且为布尔类型,防止恶意传参
if (targetProp == null || targetProp.PropertyType != typeof(bool))
    throw new ArgumentException("指定的布尔属性不存在");

// 构造 r => r.目标属性 == true 的lambda表达式
var param = Expression.Parameter(entityType, "r");
var propAccess = Expression.Property(param, targetProp);
var condition = Expression.Equal(propAccess, Expression.Constant(true));
var filterLambda = Expression.Lambda<Func<GuestModel, bool>>(condition, param);

var test = await _context.GuestModel
    .Include(r => r.PatientModel)
    .OrderByDescending(r => r.GuestLastName)
    .Where(filterLambda)
    .ToListAsync();
return test;

注意:动态构造表达式必须做严格的属性校验,只开放你允许被筛选的属性,避免被恶意传入其他属性名导致数据泄露或者查询异常。

内容的提问来源于stack exchange,提问作者WreckingCrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 13:42:30