【发布时间】:2018-05-18 11:36:16
【问题描述】:
我的模型只有 3 个类:User、Filter 和 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; }
}
Filter 是持久化到数据库的过滤器,您可以将其视为过滤器的定义。它包含一个或多个定义过滤器的FilterEntries。包含和排除是适用于过滤器的限制。
一个例子:
var filter = new Filter
{
Inclusions = new[] { new FilterEntry { Age = 33 } },
Exclusions = new[] { new FilterEntry { Name = "John" }, new FilterEntry { Name = "Peter" } },
};
这定义了一个Filter,它将代表 33 岁的人,除了被称为“约翰”或“彼得”的人。因此,当将此过滤器应用于用户时,它应该返回所有 33 岁的用户,除了 Johns 和 Peters。
现在的问题。如何使用实体框架创建一个查询,给定一个过滤器,根据它返回用户?
我什至不知道如何开始!我只有这个:
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;
注意,Filter 和 FilterEntry 保持 1-N 关系。我省略了键以简化代码。
【问题讨论】:
-
过滤器是否总是名称/年龄,或者您是否排除了其他过滤器要求?
-
是的,为了简单起见,我排除了一些过滤器,但例如,FilterEntry 可以包含一个导航属性,例如 Country,如果它被指定,它将指定一个包含/排除的 Country。 FilterEntry 的任何属性中的空值意味着未设置给定的过滤器字段。例如,所有属性都为 null 的 FilterEntry,但使用 Country 意味着只有 Country 将适用。这就是 Age 可以为空的原因。 Null 确定何时对成员应用过滤器。
标签: c# entity-framework filter entity-framework-core