Entity Framework Core Tutorial 投影
介绍
投影是一种将完整实体转换为具有这些属性子集的C#类的方法。它用于创建一个查询,该查询从模型中的一组实体中进行选择,但返回不同类型的结果。
- 投影查询可提高应用程序的效率,因为只从数据库中检索特定字段。
- 获得数据后,可以根据需要在输出之前对数据进行投影或过滤。
- 您可以使用
Select()
LINQ语句进行投影。
匿名类型
匿名类型提供了一种在不初始化的情况下创建新类型的简便方法。投影查询将数据加载到此匿名类型中。
var customer = context.Customers .Select(cust => new { Id = cust.CustomerId, FullName = cust.FirstName + cust.LastName, InvoiceList = cust.Invoices }).ToList();
在此示例中,客户数据被投影到匿名类型,其中包含Id
, FullName
和InvoiceList
。
混凝土类型
您还可以编写Projection查询以返回Concrete Type,为此,我们必须首先创建一个自定义类,并且它必须具有我们想要从表中返回的所有属性。
public class CustomerData { public int Id { get; set; } public string FullName { get; set; } public List<Invoice> InvoiceList { get; set; } }
现在更改查询中的select子句以将结果映射到CustomerData。
List<CustomerData> customers = context.Customers
.Select(cust => new CustomerData
{
Id = cust.CustomerId,
FullName = cust.FirstName + cust.LastName,
InvoiceList = cust.Invoices
}).ToList();