如何解决如何重载 LINQ IQueryable<TEntity> Where() 以接受列名
我想修改以下内容以接受将在 Where 方法中搜索的列名,例如:
public TEntity GetEntity(int val)
{
TEntity entity = _DbContext.Set<TEntity>()
.Where(e => e.Id == val)
.FirstOrDefault();
return entity;
}
改成
public TEntity GetEntity(int val,string colName)
{
TEntity entity = _DbContext.Set<TEntity>()
.WhereWithColName(val,colName)
.FirstOrDefault();
return entity;
}
表达树对我来说还是太复杂了...
解决方法
好的,解决了:
class Meta:
model = Product
extra_kwargs = {
"image": {
"error_messages": {
"required": "Please upload a photo image"
}
}
}
然后调用函数是:
public static IQueryable<TEntity> WhereById<TEntity,TKey>(this IQueryable<TEntity> query,TKey value,string colName)
where TEntity : class
{
var param = Expression.Parameter(typeof(TEntity),"e");
var propAccess = Expression.PropertyOrField(param,colName);
var valExpr = Expression.Constant(value);
var predicate = Expression.Equal(propAccess,valExpr);
var predicateLambda = Expression.Lambda<Func<TEntity,bool>>(predicate,param);
return query.Where(predicateLambda);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。