我为LINQ查询定义了以下实体类:
public class Application
{
public Application() { }
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public System.DateTime DateTimeCreated { get; set; }
public System.DateTime? DateTimeModified { get; set; }
public Employee CreatedBy { get; set; }
public Employee ModifiedBy { get; set; }
}
public class Employee
{
public Employee() { }
public string EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
我创建了以下查询来创建Application
对象并尝试为Employee
和' ModifiedBy'创建CreatedBy
实体。属性。有时,ModifiedBy
列可以包含null,我想将ModifiedBy
属性设置为null。
var query = from a in context.Applications
join u1 in context.Employees on a.CreatedBy equals u1.Employee_ID.Trim()
join u2 in context.Employees on a.ModifiedBy equals u2.Employee_ID.Trim()
where a.ApplicationId == applicationId
select new Entity.Application
{
Id = a.ApplicationId,
Name = a.ApplicationName,
Description = a.ApplicationDesc,
DateTimeCreated = a.DateTimeCreated,
CreatedBy = new Entity.Employee{ EmployeeID = a.CreatedBy, FirstName = u1.First_Name, LastName = u1.Last_Name },
DateTimeModified = a.DateTimeModified ?? null,
ModifiedBy = (a.ModifiedBy != null) ? new Entity.Employee { EmployeeID = a.ModifiedBy, FirstName = u2.First_Name, LastName = u2.Last_Name } : (Entity.Employee) null,
};
当我调试上面的查询时,我收到以下错误:
由于存在,因此无法确定条件表达式的类型 员工之间没有隐含的转换'和'应用程序'
如何解决此错误?
答案 0 :(得分:3)
它可能无法直接解决您收到的错误,但您根本不需要该查询,因为您已设置了导航属性。请改用Include
,它应该可以正常工作 - EF将为您加入必要的连接:
var query context.Applications
.Include("ModifiedBy")
.Include("CreatedBy")
.Where(a => a.ApplicationId == applicationId);
答案 1 :(得分:2)
我注意到的一些事情
join u1 in context.Employees on a.CreatedBy equals u1.Employee_ID.Trim()
join u2 in context.Employees on a.ModifiedBy equals u2.Employee_ID.Trim()
您无法像这样加入,因为CreateBy
和ModifiedBy
的类型为Employee
,而不是string
另外,请看一下:
(Entity.Employee) null
您无法将null转换为Employee
。您可能希望将来使用该类型的默认值:
default(Entity.Employee)
<强>更新强>
正如评论中指出的那样,将null转换为Entity.Employee
是合法的,但是因为你最终得到null,所以这个练习没什么意义。 default(Entity.Employee)
也会导致null,因为这是引用类型的默认值,但default
可以为其他各种类型提供不同的值,这有时可能很有用。
答案 2 :(得分:0)
经过一些额外的研究,这里是修改后的代码片段,最终为我工作:
var result = (from a in context.Applications
join u1 in context.Employee on a.CreatedBy equals u1.Employee_ID.Trim()
join u2 in context.Employee on a.ModifiedBy equals u2.Employee_ID.Trim() into us
from u2 in us.DefaultIfEmpty()
where a.ApplicationId == applicationId
select new Entity.Application()
{
Id = a.ApplicationId,
Name = a.ApplicationName,
Description = a.ApplicationDesc,
DateTimeCreated = a.DateTimeCreated,
CreatedBy = new Entity.Employee
{
EmployeeID = a.CreatedBy,
FirstName = u1.First_Name,
LastName = u1.Last_Name
},
DateTimeModified = a.DateTimeModified ?? null,
ModifiedBy = new Entity.Employee
{
EmployeeID = a.ModifiedBy ?? string.Empty,
FirstName = u2.First_Name ?? string.Empty,
LastName = u2.Last_Name ?? string.Empty
}
}).Single();