How can I join two tables in Entity Framework

asp.net-mvc database entity-framework entity-framework-6 linq

Question

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

1
0
3/10/2020 12:06:10 PM

Popular Answer

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);
0
3/10/2020 12:00:13 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow