如何在实体框架上实现左连接

时间:2014-08-08 08:55:20

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

无论加入的实体是否匹配,我都会遇到从联系人返回记录的问题。我试图实现相当于左连接。

问题是查询仅在联系人在所有相关表中包含关系时才有效。无论相关实体中的连接记录如何,我都希望返回联系人记录。

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");

1 个答案:

答案 0 :(得分:0)

感谢Serve建议正确的道路!

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

      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();
相关问题