Fetch foreign key table data

Viewed 286

While fetching data from dbcontext this.dbcontext.JobDetails.GetAll(). Here I also need data from a foreign key table that is likes for current jobDetails.

public class Like
{
    public int LikeId { get;  set; }
    public JobDetails JobDetails { get; set; }
    [ForeignKey("JobDetailFK")]
    public int JobDetailId { get; set; }
}
public class JobDetails
{
    [Key]
    public int JobDetailId { get; set; }
    public ICollection<Like> Likes { get; set; }
}
2 Answers

In Entity Framework 6 you can do it like this:

using (DatabaseContext context = new DatabaseContext()) {
    return context.JobDetails.Include(x => x.Likes).ToList();
}

To expand on the answer provided, you can also get several lists and even nested data.

List<item> items = db.mainData
    .Where(x => x.parentId == id)
    .Include(x => x.moreData)
            .ThenInclude(acc => acc.field)
    .Include(x => x.evenMoreData)
            .ThenInclude(acc => acc.field)
    .ToList();
Related