如何在实体框架上实现左连接
本文关键字:实现 连接 框架 实体 | 更新日期: 2023-09-27 18:16:59
无论连接实体是否匹配,我都有一个从Contacts返回记录的问题。我正在尝试实现左连接的等效。
问题是,只有当联系人在所有相关表中包含一个关系时,查询才有效。我想返回联系人记录,而不考虑相关实体中的连接记录。
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");
感谢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();