[英]Entity Framework - Handling a join with no records from join table
我一直在努力尋找答案,但是找不到(或理解)解決方案。 我有一個查詢,我要聯接到另一個可能有關聯記錄的表。 這是查詢:
var educationUniversity = result.new_educationUniversity.Select(c => new
{ c.majorDegree, c.dateEnd, c.dateStart, c.institutionName,
c.degreeProgramCompletionStatus, c.institutionAddress,
attachmentId = c.attachmentId ?? 0,
fileName = c.new_attachments.fileName ?? "No Attachment"}).ToList();
第一個表是“ new_educationUniversity”,其中包含用戶的大學或大學學位的詳細信息。 用戶可能已上傳或未上傳附件(該附件存儲在“ new_attachments”表中)。 attchmentID是“ new_attachments”表中的主鍵,而是“ new_educationUniversity”表中的外鍵。 EF看到了這種關系。
我將結果綁定到中繼器,但是如果沒有相關的附件,代碼將在上面的行中失敗。 如果有附件或刪除對fileName的引用,則一切正常。
上面,我正在處理fileName是否為NULL(或者至少我嘗試這樣做),但是我懷疑我的問題是該記錄根本不存在,這與我猜想的NULL不同。 我嘗試使用類似的東西:c.new_attachments.fileName.SingleOrDefault()或DefaultIfEmpty(),但是沒有運氣。
打個比方,假設您有一個CUSTOMERS表和一個ORDERS表。 您要查詢以下內容:
-客戶姓氏-客戶名字-客戶最近的訂單ID
但是,您已經注冊了從未購買任何產品的客戶。 我確定我所做的事情完全毫無意義,因此,我們非常感謝您的協助。 謝謝!
因此,您在這里發生了一些事情:
有什么解決方案? 我將創建一個局部類,以向您的new_educationUniversity類添加新屬性。 添加一個null-reference-safe屬性引用,以確定new_educationUniversity的new_attachments屬性的文件名。 然后,將轉發器綁定到新屬性。 就像是:
public partial class new_educationUniversity {
public String AttachmentFileName {
get {
if (new_attachments == null)
return "";
else
return new_attachments.fileName;
}
}
}
以下代碼行似乎有效。
var educationUniversity = result.new_educationUniversity.Select
(c => new { c.majorDegree, c.dateEnd, c.dateStart, c.institutionName,
c.degreeProgramCompletionStatus, c.institutionAddress, attachmentId = c.attachmentId ?? 0,
fileName = (c.new_attachments == null ? "***NO ATTACHMENT***" : c.new_attachments.fileName)}).ToList();
我不完全了解此行的含義:
fileName = (c.new_attachments == null ? "***NO ATTACHMENT***" : c.new_attachments.fileName)}
我認為它說:“如果無所不有與字符串替換‘沒有附件’,否則用的是在DB”
這可以接受嗎? 到現在為止還挺好。 謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.