简体   繁体   English

EF Core Include ThenInclude 过滤器

[英]EF Core Include ThenInclude Filter

I have the following DB Structure我有以下数据库结构

Tenant (one to many) -> Site (one to many) -> SiteUrl租户(一对多)-> 站点(一对多)-> SiteUrl

public sealed class Tenant : Entity
{
    public IReadOnlyCollection<Site> Sites => _sites?.ToList();
}

public class Site : Entity
{
    public IReadOnlyCollection<SiteUrl> Urls => _urls?.ToList();
}

I am trying to query the data using EF core 5.0 with the following我正在尝试使用 EF core 5.0 查询数据,如下所示

var t = await tenants
                    .Include(t => t.Sites)
                    .ThenInclude(s => s.Urls.Where(su => su.Url == url))
                    .ProjectTo<TenantContextDto>(mapper.ConfigurationProvider)
                    .FirstOrDefaultAsync();

Basically im trying to get a tenant based on the url of a site and im not getting the results back im expecting.基本上,我试图根据网站的 url 获取租户,但我没有得到我期望的结果。 I have tried all kinds of variations of the code but have not been able to get it to find the correct tenant / site based on the url being searched for.我已经尝试了代码的各种变体,但无法根据正在搜索的 url 找到正确的租户/站点。

Any help / advice would be much appreciated任何帮助/建议将不胜感激

Thanks for all the replies all谢谢大家的回复

In the DB I have Tenant 1在数据库中我有租户 1

When I search for localhost I get back the correct Tenant, Correct Site but I get the url localhost1.当我搜索 localhost 时,我得到了正确的租户、正确的站点,但我得到了 url localhost1。

Gert Arnold: Thanks totally forgot that projection ignores includes, that was a great article you pointed me at thanks. Gert Arnold:谢谢你完全忘记了投影忽略包含,这是一篇很棒的文章,你指给我谢谢。

If you want tenants that have a matching site URL then:如果您想要具有匹配站点 URL 的租户,则:

var t = await tenants
    .Where(t => t.Sites.Any(s=> s.Url == url))
    .ProjectTo<TenantContextDto>(mapper.ConfigurationProvider)
    .FirstOrDefaultAsync();

Include / ThenInclude are used when you want to return an entity and eager load related entities and their respective related entities respectively. Include / ThenInclude当你想分别返回一个实体和急切加载相关实体和它们各自的相关实体时使用。 When using Automapper's ProjectTo or using Linq's Select you do not need to Eager load, the projection will load the data based on what is needed.使用 Automapper 的ProjectTo或使用 Linq 的Select您不需要 Eager 加载,投影将根据需要加载数据。

If you want to filter the sites within the tenant details (DTO) to only the data that matches the URL then your projection will need to be configured to look for only the records that match the criteria.如果要将租户详细信息 (DTO) 中的站点过滤为仅与 URL 匹配的数据,则需要将投影配置为仅查找与条件匹配的记录。 If your DTO is including a structure for Sites within it, it will include all Sites for the matched Tenant, not just the site(s) with the target URL.如果您的 DTO 在其中包含站点结构,它将包含匹配租户的所有站点,而不仅仅是具有目标 URL 的站点。

不要忘记,沿着 1:M 关系走另一条路(从 M 到 1)会更简单一些:

context.SiteUrls.Where(su => su.Url == url).Select(su => su.Site.Tenant) ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM