I have a model with only 3 classes: User, Filter and FilterEntry.
class Filter
{
public List<FilterEntry> Inclusions { get; set; }
public List<FilterEntry> Exclusions { get; set; }
}
public class FilterEntry
{
public string Name { get; set; }
public int? Age { get; set; }
}
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
A Filter is filter that was persisted to the DB, you can see it like a definition of a filter. It contains one or more FilterEntries that define the filter. The Inclusions and Exclusions are the restrictions that apply to the filter.
An example:
var filter = new Filter
{
Inclusions = new[] { new FilterEntry { Age = 33 } },
Exclusions = new[] { new FilterEntry { Name = "John" }, new FilterEntry { Name = "Peter" } },
};
This defines a Filter that will represent people aged 33, except for who are called "John" or "Peter". So, when this filter is applied to the Users, it should return all the users that are 33, except for Johns and Peters.
Now the problem. How do I create a query using Entity Framework that, given a Filter, returns the Users according to it?
I don't even know how to start! All I have is this:
Filter filter = dbContext.Filters.First(x => x.FilterId == filterId);
var filteredUsers = from u in dbContext.Users
where ... // user is any of the in filter.Inclusions
where ... // user is not in any of the filter.Exclusions
select u;
NOTICE that Filter and FilterEntry keep a 1-N relationship. I omitted the keys to simplify the code.