I have Parent child one to many relationship between Alerts & Matches Table. I am stuck in applying filter on the child table property Following is the query, and scenarios is an incoming list of integers.
var groupedQuery =
from a in _clientContext.Alerts
join m in _clientContext.AlertsMatches
on a.AlertID equals m.alertID
group new { a, m } by new
{
a.AlertID,
a.AlertDate,
a.AlertScore,
} into gr
select new
{
AlertId = gr.Key.AlertID,
AlertDate = gr.Key.AlertDate,
AlertScore = gr.Key.AlertScore,
ScenarioIds = gr.Select(x => x.m.Scenario.ScenarioId).ToList(),
};
var query =
from item in groupedQuery
select new AlertsDTO
{
AlertId = item.AlertId,
AlertDate = item.AlertDate,
ScenarioIds = ScenarioIds
};
if (scenarios != null && scenarios.Length > 0)
{
// some condition to filter only alerts where some scenarioIds match
query = query.Where(w => w.ScenarioIds.Any(id => id == 2));
// another condition to filter only alerts where all scenarioIds match
query = query.Where(w => w.ScenarioIds.All(id => id == 2));
}
On the filter clause I am getting the following error
System.InvalidOperationException: The LINQ expression 'DbSet() .LeftJoin( inner: DbSet(), outerKeySelector: a => (object)a.AlertID, innerKeySelector: a0 => (object)a0.alertID, resultSelector: (a, a0) => new TransparentIdentifier<Alerts, AlertsMatches>( Outer = a, Inner = a0 )) .GroupBy(ti => new { AlertID = ti.Outer.AlertID, AlertDate = ti.Outer.AlertDate, AlertScore = ti.Outer.AlertScore }) .Select(g => new { AlertId = g.Key.AlertID, AlertDate = g.Key.AlertDate, AlertScore = g.Key.AlertScore, ScenarioIds = g .AsQueryable() .LeftJoin( inner: DbSet(), outerKeySelector: e => EF.Property<int?>(e.Inner, "ScenarioID"), innerKeySelector: s => EF.Property<int?>(s, "ScenarioID"), resultSelector: (o, i) => new TransparentIdentifier<TransparentIdentifier<Alerts, AlertsMatches>, Scenario>( Outer = o, Inner = i )) .Select(e => e.Inner.ScenarioID) .Distinct() .ToList() }) .Where(e1 => e1.ScenarioIds .Any(id => id == 2))' could not be translated
And below are the respective classes
public class AlertsDTO {
public int AlertId {get;set;}
public DateTime AlertDate {get;set;}
public string Scenario {get;set;}
}
public class Scenario {
public int ScenarioId {get;set;}
public string ScenarioName {get;set;}
}
public class Alerts{
public int AlertID {get;set;}
public DateTime AlertDate {get;set;}
public int AlertScore {get;set;}
}
public class AlertsMatches
{
public int alertID { get; set;}
public Scenario Scenario {get;set;}
}
See below. I did not test so it may need some minor changes