LINQ动态查询里面

时间:2018-08-22 14:06:59

标签: c# sql entity-framework linq reflection

我想动态地更改查询的特定部分-取决于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);

1 个答案:

答案 0 :(得分:0)

您可以创建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);