AlexGH AlexGH - 1 month ago 24
C# Question

Linq Include not loading List

I've been for a while trying to find out why the

Include
clause is not loading the related collection: I have two classes with a one-to-many relationship:

public class AgencyNote : IAutId
{
[Key]
public int aut_id { get; set; }
public string Comment { get; set; }
[DisplayName("Note Created Date")]
public DateTime NoteDate { get; set; }
[DisplayName("Contact Date")]
public DateTime ContactDate { get; set; }
[ForeignKey("tbl_agency")]
public int AgencyId { get; set; }
[DisplayName("User")]
public string RipsUser { get; set; }
public virtual ICollection<AgencyNoteAttachment> AgencyNoteAttachments { get; set; }
public virtual tbl_agency tbl_agency { get; set; }
}


and

public class AgencyNoteAttachment
{
[Key]
public int aut_id { get; set; }
public string Url { get; set; }
public string FileName { get; set; }
public int AgencyNoteId { get; set; }
[NotMapped]
[ForeignKey("AgencyNoteId")]
public virtual AgencyNote AgencyNote { get; set; }
}


Context class:

public DbSet<AgencyNote> AgencyNotes { get; set; }

public DbSet<AgencyNoteAttachment> AgencyNoteAttachments { get; set; }


This is the action where I'm using the
Include
clause:

private IQueryable<AgencyNote> GetNotes(int agencyId)
{
return _ctx.AgencyNotes.Include(a => a.tbl_agency).Include(a => a.AgencyNoteAttachments).OrderByDescending(f => f.NoteDate).Where(x => x.AgencyId == agencyId);
}


I'm getting
AgencyNotesAttachments
always
null
from this action even if I know it's not null, what's going on? Any question let me know...

Answer

If you add just the navigation properties between the related entities, then EF will create the FK column for you in the AgencyNoteAttachment table. Now, EF by convention can interpret AgencyNoteId is the FK of that relationship, but is good idea do that explicitly as you already have in your model or using ForeignKey attribute on FK property:

public class AgencyNoteAttachment
{        
    [Key]
    public int aut_id { get; set; }
    public string Url { get; set; }
    public string FileName { get; set; } 

    [ForeignKey("AgencyNote")]       
    public int AgencyNoteId { get; set; }

    public virtual AgencyNote AgencyNote { get; set; }        
}