【发布时间】:2010-02-23 16:29:08
【问题描述】:
我有一个由员工和学生实施的 IPerson。我真正想要的是你在下面看到的。一个 LINQ 语句来获取每种类型的 IPerson。在我调用该方法之前,这很有效;)。
我为什么会收到错误是有道理的,但我真的很难找到一种体面的方法来从数据库中提取所有 IPerson 对象并避免在我的应用程序中放置 switch 语句。
public IQueryable<IPerson> getPersons() {
// gives Types in Union or Concat have different members assigned error
var people = from p in db.Persons select p;
var students = (from s in people
where s.TypeId == (int)PersonType.Student
select new Student
{
Id = s.Id,
Age = s.Age.GetValueOrDefault(0),
Name = s.Name,
Major = s.Student.Major ?? "None",
CreditHours = s.Student.CreditHours.GetValueOrDefault(0),
PersonType = (PersonType)s.TypeId
}).Cast<IPerson>();
var employees = (from e in people
where e.TypeId == (int)PersonType.Employee
select new Employee
{
Id = e.Id,
Age = e.Age.GetValueOrDefault(0),
Name = e.Name,
PersonType = (PersonType)e.TypeId,
Salary = e.Employee.Salary.GetValueOrDefault(0)
}).Cast<IPerson>();
return students.Concat<IPerson>(employees);
//return (students.ToList()).Concat<IPerson>(employees.Cast<IPerson>().ToList()).AsQueryable<IPerson>();
}
上面,有一个注释掉的 return 语句 - 本质上是执行 .ToList() 并放弃整个延迟执行的事情,创建 2 个 SQL 语句 - 不理想。
【问题讨论】:
标签: c# asp.net linq linq-to-sql