2015-04-23 217 views
4

我有一個ticket實體,它具有ticketNotes(0到很多),並且希望在我查詢票據時撤回誰創建每個筆記的用戶詳細信息。實體框架查詢包含實體集合的子實體

我使用下面的代碼來查詢機票

var ticket = (from t in context.Tickets 
.Include(t=>t.Site) 
.Include(t=>t.Caller) 
.Include(t=>t.Caller.Site) 
.Include(t => t.Notes) 
.Include(t=>t.OpenedByUser) 
select t).First(t => t.TicketId == ticketId); 

TicketNote類是:

public class TicketNote 
{ 
    public Guid TicketNoteId { get; set; } 
    public string NoteText { get; set; } 
    public DateTime CreatedTime { get; set; } 
    public Guid TicketId { get; set; } 
    public virtual Ticket Ticket { get; set; } 
    public bool ReadOnly { get; set; } 
    public DateTime? DateTimeDeleted { get; set; } 
    public Guid TenantId { get; set; } 

    [Required] 
    [DefaultValue(typeof(Guid), "00000000-0000-0000-0000-000000000000")] 
    public Guid CreatedByUserId { get; set; } 
    [ForeignKey("CreatedByUserId")] 
    public virtual User CreatedByUser { get; set; } 
} 

我想補充

.Include(t => t.Notes.CreatedByUser)

然而,由於票據是一個集合我沒有得到選擇。

請建議最好的方法來實現撤回目前爲NULL的CreatedByUser。

感謝

+0

不確定是否有'Any()'在這裏工作 - '.Include(t => t.Notes.Any()。CreatedByUser)'? – Kami

+0

嗨,謝謝我只是試過這個,但我沒有任何實體選項,因此它不起作用。 –

+0

也許這篇文章會幫助你:[鏈接](http://www.codeproject.com/Articles/788559/Loading-Related-Entities-with-Entity-Framework-A-B)。特別是有關顯式加載的部分 – sszarek

回答

2

您可以包含更復雜的語句以獲取多級集合。請嘗試以下操作:

.Include(t => t.Notes.Select(n => n.CreatedByUser)) 
+0

偉大的作品! –

0

你有ticket變量,其內部都有財產Notes。 對於您可能使用的性能

ticket.Notes.Select(t => n.CreatedByUser) 
+0

請您在退票時告訴我們如何使用它?我在存儲庫中返回票證實體,因此在關閉上下文時不能再調用select。 –