【问题标题】:linq query dynamically inside wherelinq 在 where 内动态查询
【发布时间】:2018-08-22 14:06:58
【问题描述】:

我想动态更改查询的特定部分 - 取决于 if 条件的结果。我很乐意为您提供帮助:

if (someCondition == true)
    var ADDITION_FILTER_CRITERIA = && z.t.Name == Keyword
else
    var ADDITION_FILTER_CRITERIA = "";

var ToursPerDestination = await _context.Tours
    .Join(_context.CruiseDestinations, t => t.DestinationId, d => d.DestinationId, (t, d) => new { t, d })
    .Where(z => z.d.CruiseId == SelectedCruise.CruiseId ADDITION_FILTER_CRITERIA )
    .Select(z => new ToursViewModel()
    {                   
        Name = z.t.Name,                   
    }).OrderByDescending(z => z.Name).ToListAsync().ConfigureAwait(false);

【问题讨论】:

标签: c# sql entity-framework linq reflection


【解决方案1】:

您可以创建一个Func<string, bool> 并根据someCondition 决定它检查的内容:

Func<string, bool> ADDITION_FILTER_CRITERIA;
if (someCondition == true)
    ADDITION_FILTER_CRITERIA = (string s) => s == Keyword;
else
    ADDITION_FILTER_CRITERIA = (string s) => true;

var ToursPerDestination = await _context.Tours
    .Join(_context.CruiseDestinations, t => t.DestinationId, d => d.DestinationId, (t, d) => new { t, d })
    .Where(z => z.d.CruiseId == SelectedCruise.CruiseId && ADDITION_FILTER_CRITERIA(z.t.Name) )
    .Select(z => new ToursViewModel() { Name = z.t.Name }).OrderByDescending(z => z.Name).ToListAsync().ConfigureAwait(false);

【讨论】:

  • 太棒了!谢谢!!
猜你喜欢
  • 1970-01-01
  • 2013-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-30
相关资源
最近更新 更多