我该如何在linq to entities中组合select语句以将结果投影成匿名类型?
假设我有以下实体:
public class Address
{
public string City { get; set; }
public int ZipCode { get; set; }
//other properties
}
public class Person
{
public string Name { get; set; }
public Address Address { get; set; }
//a LOT of other properties
}
//extend person class with employee specific properties
public class Employee : Person
{
public double Salary { get; set; }
public Person Manager { get; set; }
}
有时候我只需要请求我的Person类的几个属性:
Context.Persons.Where(...).Select(p => new
{
p.Name,
PersonCity = p.Address.City,
//other needed properties
});
我需要请求与我的雇员类相同的属性,再加上特定的属性:
Context.Employees.OfType<Employee>().Where(...).Select(e => new
{
e.Salary,
ManagerName = e.Manager.Name,
e.Name,
PersonCity = e.City.Name,
//other needed properties identical as the previous select with Person entity
});
通过表达式树操作(或其他解决方案),是否可能将两个select子句合并,以避免从我的Person实体中重复所有select子句?
类似于这样:
var personSelect = p => new {
p.Name,
PersonCity = p.Address.City,
//other needed properties
};
var employeeSelect = personSelect.Combine(e => new {
e.Salary,
ManagerName = e.Manager.Name
});
context.Employees.OfType<Employee>().Where(...).Select(employeeSelect).FirstOrDefault();
// returns an anonymous object
// {
// Name = "Joachim",
// PersonCity = "Lyon",
// <other Person properties>
// Salary = 65432.10,
// ManagerName = "Samuel"
// }
Expression<Func<TInput2, TOutput2>> Combine<TInput1, TInput2, TOutput1, TOutput2> (Expression<Func<TInput1, TOutput1>> e1, Expression<Func<TInput2, TOutput2>) where TInput2 : TInput1
的方法? - ShlomoemployeeSelect
中lambda创建的匿名类型不够全面,函数无法返回新的匿名类型。 - ShlomoExpression<Func<TInput2, TOutput3>> Combine<TInput1, TInput2, TOutput1, TOutput2, TOutput3> (Expression<Func<TInput1, TOutput1>> e1, Expression<Func<TInput2, TOutput2>>) where TInput2 : TInput1
,而且TOutput3
在编译时不存在。 - Shlomo