【发布时间】:2012-10-23 09:06:03
【问题描述】:
假设,我们有下一个代码:
public class Dto
{
public int Id;
public string Name;
}
...
using (var db = new NorthwindDataContext())
{
var q = from boss in db.Employees
from grunt in db.Employees.Where(p => p.ReportsTo == boss.EmployeeID).DefaultIfEmpty()
select new Dto { Id = boss.EmployeeID, Name = grunt.FirstName };
}
我想将选择器提取为表达式并将其存储在另一个地方。在方法语法中,它看起来像这样:
Expression<Func<Employee, Employee, Dto>> selector = (boss, grunt) => new Dto
{
Id = boss.EmployeeID, Name = grunt.FirstName
};
using (var db = new NorthwindDataContext())
{
var q = db.Employees.SelectMany(boss => db.Employees.Where(p => p.ReportsTo == boss.EmployeeID).DefaultIfEmpty(), selector);
}
是否可以将此 LinqToSql 方法链转换为保持 Expression 变量就地的查询语法?
UPD:
为了澄清我的问题,我使用 DefaultIfEmpty 进行左连接,它是相等查询的一种简短形式:
using (var db = new NorthwindDataContext())
{
var q = from boss in db.Employees
join stub in db.Employees on boss.EmployeeID equals stub.ReportsTo into stubi
from grunt in stubi.DefaultIfEmpty()
select new Dto { Id = boss.EmployeeID, Name = grunt.FirstName };
}
正常工作,因为它使用内联表达式编译。当没有对应的grunt 时,它将null 分配给名称字段。但是如果通过调用外部映射器方法重写此查询,它将被编译为方法调用,这将获得可空的grunt参数并导致NullReferenceException:
public static Dto GetDto(Employee boss, Employee grunt)
{
return new Dto
{
Id = boss.EmployeeID,
Name = grunt.FirstName
};
}
using (var db = new NorthwindDataContext())
{
var q = from boss in db.Employees
join stub in db.Employees on boss.EmployeeID equals stub.ReportsTo into stubi
from grunt in stubi.DefaultIfEmpty()
select GetDto(boss, grunt);
}
当然,我可以在映射器方法中添加空检查,但我在 DAL 中试图实现的是将选择器提取到映射器类中,并可能在那里省略空检查。
【问题讨论】:
标签: c# linq linq-to-sql linq-query-syntax