1

Hey I have two following classes:

public class Project 
{
  public int Id { get; protected set; } 
  public string ProjectName { get; protected set; }
  public List<Task> TaskList{ get; protected set; }  
}

public class Task
{
  public int Id { get; protected set; }
  public int ProjectId { get; protected set; }
  public string Name { get; protected set; } 
}

If I am using Entity Framework is it possible to get Project object from database (eg. by id) and in the same time join tasks list into [Project] TaskList property, or I should first get a project, and then tasks?

How it should be implemented properly?

bielu000
  • 1,826
  • 3
  • 21
  • 45

2 Answers2

2

If you described relationship between tables Project and Task as explained here than you can directly just call your Project entity; it will come with a list of related Tasks; if you didn't described relationships than you have to create a join query by linq to etnity or use .Inlcude for relate entites to each other.

var tasks = (from items in db.Task
join projects in db.Project on items.ProejctId equals projects.Id
where 1==1 // you can add some other confitions to here
select new SelectItemsList() { //Items you want to select })
nzrytmn
  • 6,193
  • 1
  • 41
  • 38
2

Do you require the Project class object like below code? without using .include<>

var res = (from p in db.ProjectTable
          select new Project
          {
              Id = p.Id,
              ProjectName = p.ProjectName,
              TaskList = (from q in db.TaskTable
                         where q.ProjectId = p.Id
                         select q
                      ).ToList()
          }).ToList();
 return res;  //you will get List<Project> with their List<TaskList>