我有一个模型:List<PROJECT>
PROJECT
- &gt;有List<TASK>
TASK
- &GT;有List<SUBTASK>
将分别从Project,Task,Subtask表中填充数据,并参考每个数据。
使用分页填充此模型的有效方法是什么?
我正在实施的内容:
此解决方案工作正常,但需要多次数据库调用。
更新
public List<Project> GetProject(int page=1, int pageSize=10)
{
List<Project> _lstProject = new List<Project>();
try
{
using (DevEntities db = new DevEntities())
{
_lstProject = db.ProjectSelect(page, pageSize).Select(m => new Project()
{
ProjectId = m.ProjectID,
ProjectNumber = m.ProjectNo,
TaskList = GetTaskDetails(m.ProjectID)
}).ToList();
}
return _lstProject ;
}
catch (Exception e)
{
throw;
}
finally
{
_lstProject = null;
}
}
public List<Task> GetTaskDetails(ProjectID)
{
List<Task> _lstTask = new List<Task>();
try
{
using (DevEntities db = new DevEntities())
{
_lstTask = db.TaskSelect(ProjectID).Select(m => new Task()
{
TaskId = m.TaskID,
TaskNumber = m.TaskNo,
SubTaskList = GetSubTaskDetails(m.TaskID)
}).ToList();
}
return _lstTask ;
}
catch (Exception e)
{
throw;
}
finally
{
_lstTask = null;
}
}
public List<SubTask> GetSubTaskDetails(int TaskID)
{
List<SubTask> _lstSubTask = new List<SubTask>();
try
{
using (DevEntities db = new DevEntities())
{
_lstSubTask = db.TaskSelect(TaskID).Select(m => new SubTask()
{
SubTaskId = m.SubTaskID,
SubTaskNumber = m.SubTaskNo
}).ToList();
}
return _lstSubTask ;
}
catch (Exception e)
{
throw;
}
finally
{
_lstSubTask = null;
}
}
答案 0 :(得分:2)
在我看来,为了优化您的代码,您有两个有效的选项:
选项1:
每种实体类型的一个查询(共3个查询):
var projects = db.Projects.Where().Order().Skip().Take().Select().ToList(); // 1 query
var projectIds = projects.Select(x => x.ProjectId).ToList();
var tasks = db.Tasks.Where(x => projectIds.Contains(x.ProjectId)).Select().ToList(); // 1 query
var taskIds = tasks.Select(x => x.Id).ToList();
var subtasks = db.Tasks.Where(x => taskIds.Contains(x.TaskId)).Select().ToList() // 1 query
foreach(var project in projects)
{
project.Tasks = tasks.Where(x => x.ProjectId == project.ProjectId).ToList();
// etc
// complete hierarchy structure
}
选项2:
一个带有2个左外连接的查询:
var projects = (from proj in db.Projects.Where()
join t in db.Tasks on t.ProjectId equals proj.ProjectId into tasks
from task in t.DefaultIfEmpty()
join s in db.Tasks on s.TaskId equals task.Id into subtasks
from subtask in subtasks.DefaultIfEmpty()
select new
{
ProjectId = proj.ProjectId,
TaskId = task.Id,
SubtaskId = subtask.Id
}).ToList(); // 1 query
// etc
// proceed with creating hierarchy structure using GroupBy
这两者中的哪一个更有效率?
这取决于。我相信有很多人比较喜欢一个人,我真的很乐意听到他们的意见。
我的个人经验告诉我通常选择选项1 ,但您应该根据您的数据量和数据库配置(索引,fks)对它们进行测试和计时并自己决定