使用Linq to Entities (EF6) 动态选择列名
使用Linq to Entities (EF6) 动态选择列名
我希望封装使用EF6时的常见场景。这是一个例子:
public class StringRequest : DbRequestProperty { public string Name { get; set; } public bool? ExactMatch { get; set; } protected override bool IsValid() { return !string.IsNullOrWhiteSpace(Name); } private bool RequestExactMatch() { return ExactMatch.HasValue && ExactMatch.Value; } protected override IQueryableExecute (IQueryable original, string propertyName) { return RequestExactMatch() ? original.Where(o => GetProperty (o, propertyName) == Name) : original.Where(o => GetProperty (o, propertyName).Contains(Name)); } }
但是GetProperty无法转换为查询。所以我想动态选择使用"propertyName"作为列名。
protected override IQueryableExecute (IQueryable original, string propertyName) { return RequestExactMatch() ? original.Where(o => GetColumnByName (propertyName) == Name) : original.Where(o => GetColumnByName (propertyName).Contains(Name)); }
这样做可能吗?提前感谢。
原因:问题的出现是因为在使用LINQ to Entities(EF6)时,需要动态选择列名,但是无法直接在LINQ查询中使用字符串来选择列名。
解决方法:通过使用Expression类,可以动态创建Expression
对于日期,可以通过在数据库部分截断时间部分来仅比较日期。可以使用转换函数或类型转换来实现。根据提供的参考链接,可以找到具体的实现方法。