【问题标题】:Ef Core 3.1 Getting Customers with optional contactsEf Core 3.1 通过可选联系人获取客户
【发布时间】:2020-09-15 16:19:02
【问题描述】:

我有一个模型,客户可以有 0..N 个联系人。 联系关系有一个 ContactType。 “主要”、“报告接收者”或“未设置”。

0 = '未设置' 1 = '主要联系人' 2 = '报告接收者'

我想要:

  • 所有客户,即使没有联系人
  • 只有主要联系人,如果有的话。如果有两个只有第一个(如果可能的话)。

这就是我现在所拥有的。但当然,它只会返回具有主要联系人的客户。

var customers= ctx.Customers
    .Include(x => x.CustomerContacts)
    .Where(x => x.CustomerContacts.Any(y => y.ContactTypeId == 1))
    .ToList();

现在我已经使用以下 sql 创建了一个视图:

select c.ID CustomerId, c.NAME CustomerName, ctype.NAME CustomerType,   ct.NAME ContactName, ct.EMAIL ContactEmail, ct.PHONE ContactPhone from CUSTOMER c
left outer join CUSTOMER_TYPE ctype on c.CUSTOMER_TYPE_ID = ctype.ID
left outer join CUSTOMER_CONTACT_MAP map on c.id = map.customer_id and map.CONTACT_TYPE_ID = 1
left outer join CUSTOMER_CONTACT ct on ct.ID = map.CONTACT_ID
order by c.NAME;

提示!我认为 DefaultIfEmpty 可能是解决左外连接问题的关键。

我正在为 ef core 3.1 使用新的 Oracle 提供程序

【问题讨论】:

    标签: lambda entity-framework-core


    【解决方案1】:

    我认为您最不坏的选择(除了等待 EF Core 5 中的过滤包含)是将客户和主要联系人查询到包装对象的单独属性中。您的查询可能如下所示:

    var results = ctx.Customers
         .Select(c => new {
            Customer = c,
            PrimaryContact = c.CustomerContacts.Where(cc => cc.ContactTypeId == 1).FirstOrDefault()
         }).ToList();
    

    如果有多个使用 OrderBy 的联系人,您可能还应该指定要获取的类型 1 的哪个联系人

    【讨论】:

      猜你喜欢
      • 2022-11-18
      • 2023-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      相关资源
      最近更新 更多