【问题标题】:How to achieve left join on entity framework如何在实体框架上实现左连接
【发布时间】:2014-08-08 08:55:20
【问题描述】:

无论加入实体是否匹配,我都无法从联系人返回记录。我正在尝试实现相当于左连接。

问题是只有在联系人包含所有相关表中的关系时查询才有效。无论相关实体中的加入记录如何,我都想返回联系人记录。

var SubQuery = from Contacts in db.Contacts
               join ContactAddictions in db.ContactAddictions.DefaultIfEmpty()
                    on Contacts.ID equals ContactAddictions.ContactID
               join ContactTreatmentPreferences in db.ContactTreatmentPreferences.DefaultIfEmpty()
                    on Contacts.ID equals ContactTreatmentPreferences.ContactID
               join TreatmentHistories in db.TreatmentHistories.DefaultIfEmpty()
                    on Contacts.ID equals TreatmentHistories.ContactID
               where
                    Contacts.ID == ID
               select Contacts;

var Query = SubQuery.Include("ContactAddictions")
    .Include("ContactTreatmentPreferences")
    .Include("ContactAddictions.Tag")
    .Include("ContactTreatmentPreferences.Tag")
    .Include("TreatmentHistories")
    .Include("TreatmentHistories.TreatmentCenter")
    .Include("ContactDispositionType")
    .Include("State");

【问题讨论】:

  • 你的意思是 Left OUTER Join like in msdn.microsoft.com/en-us/library/bb397895.aspx ?
  • 你没有说明你的问题是什么......
  • 问题是只有当联系人在所有相关表中都包含关系时查询才有效。无论相关实体中的加入记录如何,我都想返回联系人记录。
  • 所以你不想加入,因为你不关心加入。您只需选择所有表格并按 ContactID 分组
  • @Serv - 我想我知道你的意思。我会试试的,谢谢你的建议。

标签: c# .net database entity-framework left-join


【解决方案1】:

感谢 Serv 提出正确的路径!

这是处理我的要求的最终查询。

      var SubQuery = from Contacts in db.Contacts
                       from ContactAddictions in db.ContactAddictions.DefaultIfEmpty()
                       from ContactTreatmentPreferences in db.ContactTreatmentPreferences.DefaultIfEmpty()
                       from TreatmentHistories in db.TreatmentHistories.DefaultIfEmpty()
                       orderby
                           Contacts.LastName, Contacts.FirstName
                       where
                            Contacts.ID == ID
                       select Contacts;

        var Query = SubQuery.Include("ContactAddictions")
            .Include("ContactTreatmentPreferences")
            .Include("ContactAddictions.Tag")
            .Include("ContactTreatmentPreferences.Tag")
            .Include("TreatmentHistories")
            .Include("TreatmentHistories.TreatmentCenter")
            .Include("ContactDispositionType")
            .Include("State");
        return Query.FirstOrDefault();

【讨论】:

    猜你喜欢
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多