【发布时间】:2013-07-05 12:03:56
【问题描述】:
我还没有在 linq 中进行 LEFT JOIN,而且我非常卡住。
目前,我有这个:
var results = (from csr
in _context.project_sprint_resource
join pr in _context.project_resource
on csr.ProjectResourceId equals pr.Id
join prpa in _context.project_resource_person_allocation
on pr.Id equals prpa.ProjectResourceId
where csr.ProjectSprintId == sprintId
select new SprintResourceDto
{
SprintId = csr.ProjectSprintId,
ProductiveHours = pr.ExpectedProductiveHours,
ProjectResourceId = pr.Id,
ResourceTypeId = pr.ResourceTypeId,
ResourceType = new ReferenceTypeDto
{
Description = pr.resource_type.Description,
Id = pr.resource_type.Id
},
AssignedHours = pr.ExpectedProductiveHours,
Person = new PersonDto
{
Id = prpa.Id,
Firstname = prpa.person.Firstname,
Surname = prpa.person.Surname
},
PersonId = prpa.PersonId
}).ToList();
return results.ToList();
我需要更改它以使“_context.project_resource_person_allocation 中的 prpa”成为 LEFT 联接,因为此表可能没有匹配的行。
看起来需要一个INTO,但我看到的例子并没有说明如何。
我的另一种选择可能是以某种方式在两个查询中执行此操作?但是,我是一个 SQL 人,但是,发现很难掌握如何在 linq 中进行 LEFT 连接。
编辑: 我已经取得了一些进展,但我遇到了最后的问题。我已经修改了查询,似乎我得到了正确的行,但是......在没有右侧行(左连接)的情况下,它崩溃了,因为我无法将 NULL 分配给我的 Person属性(这是我创建的一个类):
var results = (from csr
in _context.project_sprint_resource
join pr in _context.project_resource
on csr.ProjectResourceId equals pr.Id
join prpa in _context.project_resource_person_allocation
on pr.Id equals prpa.ProjectResourceId into sub
from subq in sub.DefaultIfEmpty()
where csr.ProjectSprintId == sprintId
select new SprintResourceDto
{
SprintId = csr.ProjectSprintId,
ProductiveHours = pr.ExpectedProductiveHours,
ProjectResourceId = pr.Id,
AssignedHours = pr.ExpectedProductiveHours,
ResourceTypeId = pr.ResourceTypeId,
PersonId = subq != null ? subq.PersonId : (int?)null,
ResourceStartDate = pr.StartDate,
ResourceEndDate = pr.EndDate,
Deleted = csr.Deleted.HasValue,
ResourceType = new ReferenceTypeDto
{
Description = pr.resource_type.Description,
Id = pr.resource_type.Id
},
Person = null
//= subq != null ? new PersonDto
// {
// Id = subq != null ? subq.Id : 0,
// Firstname = subq != null ? subq.person.Firstname : "",
// Surname = subq != null ? subq.person.Surname : ""
// } : null,
});
return results.ToList();
}
catch (Exception e)
{
var ne = e;
return null;
}
当我尝试将 NULL 分配给 Person 时发生错误。我收到一条错误消息:
无法创建类型为空的常量值 'SharedObjects.EntityObjects.PersonDto'。只有实体类型, 在此上下文中支持枚举类型或原始类型。
PersonDto 对象的定义如下:
public class PersonDto
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Surname { get; set; }
public decimal GrossSalary { get; set; }
public string FullName
{
get { return string.Format("{0} {1}", Firstname, Surname); }
}
}
【问题讨论】:
-
试试
default(Person)而不是null -
使用它,我得到:{“无法创建类型为 'SharedObjects.EntityObjects.PersonDto' 的空常量值。在此上下文中仅支持实体类型、枚举类型或原始类型。”}
-
什么是 PersonDto 类?能发一点吗?
-
我现在已经为 PersonDto 添加了类定义。
-
SprintResourceDto.Person是什么类型?