gpt4 book ai didi

c# - 将 linq 中的 select 子句组合到具有匿名类型的实体

转载 作者:太空宇宙 更新时间:2023-11-03 11:02:20 26 4
gpt4 key购买 nike

我如何将 linq 中的 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
});

而且我还需要请求我的 Employee 类的相同属性以及特定属性:

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"
// }

最佳答案

不,没有办法完全按照您的要求进行。问题是每个匿名类型都必须在编译时创建,但表达式树在运行时工作。

我可以看到两种解决方法:

  1. Employee 的匿名类型将有一个类似于 PersonData 的属性,它包含带有来自 Person 的信息的匿名类型。
  2. 您可以创建普通类型,例如 PersonDataEmployeeData(继承自 PersonData)。每种类型都可以为您提供一个表达式来创建它,EmployeeData 的表达式将根据 PersonData 的表达式进行计算。

在这两种情况下,您都需要一些表达式树管道,但这应该不难。

关于c# - 将 linq 中的 select 子句组合到具有匿名类型的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17235839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com