繁体   English   中英

在 C# 中使用 Include() 和 Linq 执行左连接

[英]Perform left join with Include() with Linq in C#

我在 C# 中遇到了 Entity Framework Core 的问题。 我创建了一个 function 来从我的数据库中返回Organisation列表。 对于每个组织,我有两张表:

  • OrganisationUser :与Organisation的链接是OrganisationId 此表使用LicenceId链接到Licence
  • InvitationOrganisation的链接是OrganisationId 此表使用LicenceId链接到Licence

如果我运行我收到的查询,如我所料,包含所有详细信息的组织列表。

public IQueryable<Organisation> GetOrganisationsByBillingDay(int billingDay)
{
    return _context.Organisation
                   .Include(org => org.OrganisationUser)
                        .ThenInclude(usr => usr.License)
                   .Include(org => org.Invitation)
                        .ThenInclude(i => i.License)
                   .Where(o => o.BillingDay == billingDay);
}

在此列表中,不包括在OrganisationUserInvitation中没有任何记录的组织。

怎么可能包括它们? 有没有比使用Linq编写查询不同的方法?

更新

如果您查看查询 Linq 会通过左连接创建它。

在此处输入图像描述

配置是

builder.Services.AddDbContext<BillingContext>(options =>
    options.UseSqlServer(configuration.GetConnectionString("BillingDatabase"),
    providerOptions => providerOptions.EnableRetryOnFailure()
));

最后更新

正如您在屏幕截图中看到的, Linq执行左连接查询。 我现在有我正在寻找的东西。 问题出在数据而不是代码中。

如果它是可选的,那么您的导航属性将是 null 或空集合,具体取决于关系的基数。 您不需要做任何特别的事情,因为Include()隐含了连接,但用户在查询本身中没有明确指定。

最可能的问题是您的关系定义。 你能分享你的 model 配置吗?

暂无
暂无

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

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