我想在我的LINQ查询中动态添加where子句。我具有过滤器属性名称和过滤器属性值,因此我需要构建如下内容:
var assignmentListQuery = context.Assignments;
if (!string.IsNullOrWhiteSpace(bookingStep.FilterPropertyName) && !string.IsNullOrWhiteSpace(bookingStep.FilterPropertyValue))
{
assignmentListQuery = assignmentListQuery.Where(item => PROPERTYNAME == PROPERTYVALUE)
}
ar assignmentList = await assignmentListQuery.ToListAsync();
我试图获取属性的propertyinfo,在这里我似乎不知道。
var item = context.Set<Assignment>().First();
object value = item.GetType().GetProperty(bookingStep.FilterPropertyName).GetValue(item, null);
有人对如何创建这种where子句有想法吗?
public class Assignment
{
/// <summary>
///
/// </summary>
[Display(Name = nameof(Id))]
public int Id { get; set; }
/// <summary>
///
/// </summary>
[Display(Name = nameof(OrderNumber))]
public string OrderNumber { get; set; }
/// <summary>
///
/// </summary>
[Display(Name = nameof(ScheduledLoading))]
public DateTime ScheduledLoading { get; set; }
/// <summary>
///
/// </summary>
[Display(Name = nameof(CustomerOrderNumber))]
public string CustomerOrderNumber { get; set; }
/// <summary>
///
/// </summary>
[Display(Name = nameof(ArticleNumber))]
public string ArticleNumber { get; set; }
/// <summary>
///
/// </summary>
[Display(Name = nameof(Comment))]
public string Comment { get; set; }
[Display(Name = nameof(CustomerId))]
public int? CustomerId { get; set; }
[Display(Name = nameof(Customer))]
public virtual Customer Customer { get; set; }
}
这是Assignment实体,FilterPropertyName例如“ CustomerOrderNumber”
答案 0 :(得分:3)
谢谢大家。我使用了它
List<Assignment> assignmentList;
if (!string.IsNullOrWhiteSpace(bookingStep.FilterPropertyName) &&
!string.IsNullOrWhiteSpace(bookingStep.FilterPropertyValue))
{
assignmentList = await
assignmentListQuery.Where(e =>
EF.Property<string>(e, bookingStep.FilterPropertyName) ==
bookingStep.FilterPropertyValue).ToListAsync();
}
else
{
assignmentList = await assignmentListQuery.ToListAsync();
}
答案 1 :(得分:1)
以@Doppelmoep答案为基础(这使我省了下来),您还可以使用特殊的EF Core EF.Functions.Like扩展名来动态生成具有动态PROPERTYNAMEs和动态SQL Like语句的SQL Like语句(带通配符-%_ [^]是类似SQL的有效通配符):
assignmentList = await
assignmentListQuery.Where(e =>
EF.Functions.Like(EF.Property<string>(e, bookingStep.FilterPropertyName),
bookingStep.FilterPropertyValue)).ToListAsync();