3

我有这些 POCO 课程:

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

我已尝试按 Id 获取任务并为此任务加载所有相关实体,但 TaskComment 和 TaskAssigned 的用户实体对于任务实体中的用户以外的其他用户为空:

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

2 回答 2

9

中的“路径”Include是包罗万象的,这意味着您可以指定用.(点)分隔的多个属性,EF 将包括“属性路径”的所有部分。

在你的情况下,这应该工作:

public Task GetTaskById(int taskId)
{
    return context.Tasks
               .Include("TaskAssigns.User")
               .Include("TaskComments.User")
               .Include("User").Where(t => t.TaskId == taskId).FirstOrDefault();
}
于 2012-08-17T10:59:02.927 回答
0

更改上下文属性如下

context.DataContext.ContextOptions.ProxyCreationEnabled = true; 
context.DataContext.ContextOptions.LazyLoadingEnabled = true;
于 2012-08-17T10:59:52.340 回答