简体   繁体   中英

Load child entities in Entity Framework

I have got these POCO classes:

public class  Task
    {
        public int TaskId { get; set; }
        public int ProjectId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime? DueDate { get; set; }
        public int UserId { get; set; }
        public string Tags { get; set; }
        public string FileName { get; set; }
        public virtual Project Project { get; set; }
        public virtual List<TaskAssigned> TaskAssigns { get; set; }
        public virtual List<TaskComment> TaskComments { get; set; }
        public virtual User User { get; set; }
    }

 public class User
    {
        public int UserId { get; set; }
        public string Name { get; set; }
        public int AccountId { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public bool IsAdmin { get; set; }
        public virtual Account Account { get; set; }
    }

public class TaskComment
    {
        public int TaskCommentId { get; set; }
        public int TaskId { get; set; }
        public int UserId { get; set; }
        public string Comment { get; set; }
        public string FileName { get; set; }
        public virtual User User { get; set; }
    }

    public class TaskAssigned
    {
        public int TaskAssignedId { get; set; }
        public int TaskId { get; set; }
        public int UserId { get; set; }
        public virtual User User { get; set; }
    }

I have tried to get task by Id and load all related entities for this task but User entity for TaskComment and TaskAssigned is null for other users than User in Task entity:

public Task GetTaskById(int taskId)
    {
        return context.Tasks.Include("TaskAssigns").Include("TaskComments").Include("User").Where(t => t.TaskId == taskId).FirstOrDefault();
    }

The "path" in the Include is all-inclusive this means you can specify multiple properties separated with a . (dot) and EF will include all the part of the "property path".

In you case this should work:

public Task GetTaskById(int taskId)
{
    return context.Tasks
               .Include("TaskAssigns.User")
               .Include("TaskComments.User")
               .Include("User").Where(t => t.TaskId == taskId).FirstOrDefault();
}

change context properties as follows

context.DataContext.ContextOptions.ProxyCreationEnabled = true; 
context.DataContext.ContextOptions.LazyLoadingEnabled = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM