I have got two tables in my project. I want to get Note with username of the note writer. How can I join this table in LINQ?
Note Entity :
public class Note : MyEntitesBase
{
public string Tittle { get; set; }
public string Text { get; set; }
public bool IsDraft { get; set; }
public bool IsApproved { get; set; }
public int CategoryID { get; set; }
public virtual EvernoteUser Owner { get; set; }
public virtual List<Comment> Comments { get; set; }
public virtual Category Category { get; set; }
public virtual List<Liked> Likes { get; set; }
public Note()
{
Comments = new List<Comment>();
Likes = new List<Liked>();
}
}
EvernoteUser Entity:
public class EvernoteUser : MyEntitesBase
{
public string Name { get; set; }
public string Surname { get; set; }
public string Username { get; set; }
/*Exc */
public Guid ActivateGuid { get; set; }
public virtual List<Note> Notes { get; set; }
public virtual List<Comment> Comments { get; set; }
public virtual List<Liked> Likes { get; set; }
}
You need to eager load the Owner table data when you make the query against Notes so that when you access the .Owner property it is not null. For example:
Note noteWithOwner = _context.Notes
.Include(x => x.Owner) // Eager load the Owner table data into the object graph.
.SingleOrDefault(x => x.ID == noteID);