4

I have a ticket entity that has ticketNotes (0 to many) and would like to pull back the user details for who created each note when I query tickets.

I use the following code to query a ticket

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

My TicketNote Class is:

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; }
 }

I would like to add

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

However as notes is a collection I don't get the option.

Please advise the best approach to achieve pulling back the CreatedByUser which is NULL at the moment.

Thanks

3
  • Not sure if Any() would work here - .Include(t => t.Notes.Any().CreatedByUser)? Commented Apr 23, 2015 at 9:22
  • Hi, Thanks I just tried this but I don't have any entity options after any so it doesn't work. Commented Apr 23, 2015 at 9:24
  • Maybe this article will help you: link. Especially parts concerning explicit loading. Commented Apr 23, 2015 at 9:27

2 Answers 2

2

You can include more complex statements to get at multilevel collections. Try the following:

.Include(t => t.Notes.Select(n => n.CreatedByUser))
Sign up to request clarification or add additional context in comments.

Comments

0

You have ticket variable which have property Notes inside it. For performance you may use

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

1 Comment

Please can you advise how to use this when returning the ticket? I return a ticket entity in my repository so can't call a select later as the context is closed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.