我已经读过许多关于该问题的变体,我无法相信我需要的解决方案是如此复杂,以至于需要使用额外的库和疯狂的技巧,希望不会!
在运行时,我项目中的LINQ查询需要动态更改,具体取决于用户要过滤的数据库表中的列数。在我的示例中,我首先显示一个有效的LINQ查询,该查询是经过硬编码的。下一个示例使用在运行时生成的列表,我需要弄清楚的是如何在不编译错误的情况下将字符串变量(whereClause)插入LINQ查询中?
工作示例(硬编码)
logs = _context.Logs.Where(s => s.Level == LogLevel & s.LogEventCategory == EventCategory)
.Select(s => new Logs()
{
TimeStamp = s.TimeStamp,
Level = s.Level,
Exception = s.Exception,
LogEventCategory = s.LogEventCategory,
LogEventType = s.LogEventType,
LogEventSource = s.LogEventSource,
LogEventName = s.LogEventName,
LogUserName = s.LogUserName,
LogForename = s.LogForename,
LogSurname = s.LogSurname,
LogData = s.LogData
});
示例二-我要修复和使用的解决方案...
首先创建一个列表,列表的内容将在每次运行新查询时更改,通过父OnGet方法作为变量传递的字符串将包含一个值并在字符串连接串联中使用,或者为null,因此不会添加到列表中并在串联中使用。
第二个例子是我得到编译错误的地方。
var filtersList = new List<string>();
if (LogLevel != null)
{
filtersList.Add("s.LogLevel == LogLevel");
}
if (EventCategory != null)
{
filtersList.Add("s.EventCategory == EventCategory");
}
var whereClause = string.Join(" & ", filtersList.ToArray());
logs = _context.Logs.Where(s => whereClause) // *HERE I WANT TO USE THE STRING VARIABLE! not working
.Select(s => new Logs()
{
TimeStamp = s.TimeStamp,
Level = s.Level,
Exception = s.Exception,
LogEventCategory = s.LogEventCategory,
LogEventType = s.LogEventType,
LogEventSource = s.LogEventSource,
LogEventName = s.LogEventName,
LogUserName = s.LogUserName,
LogForename = s.LogForename,
LogSurname = s.LogSurname,
LogData = s.LogData
});
我得到的错误是“无法将lambda表达式转换为预期的委托类型,因为该块中的某些返回类型不能隐式转换为委托的返回类型”等等
在实现之前,您只需将.Where()调用添加到查询的末尾:
query = _context.Logs.Select(s => new ..);
if (EventCategory != null) query = query.Where(e => e.EventCategory == EventCategory);
if (LogLevel != null) query = query.Where(e => e.LogLevel == LogLevel);
var items = query.ToList();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句