如何仅从Entity Framework中的对象图中选择特定属性? [英] How to only select specific properties from an object graph in Entity Framework?
问题描述
我有一个简单的数据模型
I have a simple data model
car
- make
- model
- year
- colour
- engine
- model
- no. cylinders
- size
- etc
- fuel tank
- model
- capacity
- fuel type
- etc
- etc
所以我有汽车,发动机和油箱实体。每个都有许多属性。
So I have 'car', 'engine' and 'fuel tank' entities. Each of which have many properties.
我想要列出所有100辆汽车,但只想显示以下选定的属性: car.make,car.model,car.year,car.engine,car.size,car.fueltype
。
I want a list of all the 100s of cars but only want to show the following selected properties: car.make, car.model, car.year, car.engine, car.size, car.fueltype
.
我当然可以使用 .include
来带回对象图中的子实体,但这是一个很大的成功,因为有很多属性。
I can certainly use .include
to bring back sub-entities in the object graph but this is a big hit as there are many properties.
我的问题是是否有一种整洁的方法来做到这一点。还是实际上使用实体框架(最好是EF7 / Core)的任何方式?
My question is whether there is a neat way to do this. Or any way in fact using Entity Framework (ideally EF7/Core)?
[我确实指的是 https://colinmackay.scot/2011/07/31/getting-just-the-columns-you-want-from-entity-framework/ 它使用select进入一个匿名类,但看不到它如何在多个include中起作用]
[ I did refer to https://colinmackay.scot/2011/07/31/getting-just-the-columns-you-want-from-entity-framework/ which uses the select into an anonymous class, but could not see how this could work within multiple includes ]
谢谢。
推荐答案
如果您想拉回完整实体,则只需要使用 Include
-您不要需要这些来进行投影。您可以匿名进行投影,也可以使用定义的模型类进行投影。以下代码应该使您入门:
You only need to use Include
if you want to pull the full entities back - you don't need these to do a projection. You can do a projection either anonymously, or using a defined model class. The following code should get you started:
// Define model...
public class CarModel
{
public string Make { get; set; }
public string Model { get; set; }
public int EngineCC { get; set; }
}
// Project to list of models
var cars = context.Cars.Select(c => new CarModel
{
Make = c.Make,
Model = c.Model,
EngineCC = c.Engine.CC
}).ToList();
您可以使用 AutoMapper 。使用AutoMapper,它变为:
You can make this much simpler by using a mapping library such as AutoMapper. Using AutoMapper, this becomes:
// (at start of project)
Mapper.Initialize(c => {
c.CreateMap<Car, CarModel>();
});
// Projection...
var cars = context.Cars.ProjectTo<CarModel>().ToList();
在此示例中,EngineCC是从Engine.CC自动映射的,但是您可以手动指定任何映射不只是自动工作。 AutoMapper将创建一个Linq投影,仅恢复您需要的属性。
In this example, EngineCC was automatically mapped from Engine.CC, but you can manually specify any mappings which don't just work automatically. AutoMapper will create a Linq projection, only bringing back the properties you need.
这篇关于如何仅从Entity Framework中的对象图中选择特定属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!