There is a structure:
The client has several cases and has several LOGS.
public class Client
{
public int Id { get; set; }
public IEnumerable<Case> Cases { get; set; }
}
public class Case
{
public int CaseId { get; set; }
public IEnumerable<Log> Histories { get; set; }
}
public class Log
{
public int Id { get; set; }
public string Code { get; set; }
}
I want to get customers who have all the magazines from each case. The Code property is set to "WRONG" or clients that have no logs at all. In addition, I have a few simple conditions that you can see below in a simplified form for the publication code (naturally, EF uses IQueryable instead of ICollection).
First, I tried to create an extension method called AllOrEmpty that works fine, but not in Linq for entities (it does not accept extension methods).
public static class Extensions
{
public static bool AllOrEmpty<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
return source.All(predicate) || !source.Any();
}
}
var sampleIds = new List<int>() { 1, 2, 3 };
Entities db = new Entities();
db.Clients
.Where(client => client.Cases
.Where(cas => sampleIds.Contains(cas.CaseId))
.SelectMany(cas => cas.Histories
.Where(log => log.Id < 10)
)
.AllOrEmpty(log => log.Code == "WRONG") << ideal solution
)
.Select(client => client.Id);
-, - return where clausule, , IQueryable : lambda
db.Clients
.Where(client =>
{
var logs = client.Cases
.Where(cas => sampleIds.Contains(cas.CaseId))
.SelectMany(cas => cas.Histories
.Where(log => log.Id < 10)
);
return !logs.Any() || logs.All(log => log.Code == "WRONG");
})
.Select(client => client.Id);
, - . ?