问题
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.
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
.
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.
My question is whether there is a neat way to do this. Or any way in fact using Entity Framework (ideally EF7/Core)?
[ 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 ]
Thanks you.
回答1:
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();
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();
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.
来源:https://stackoverflow.com/questions/36573224/how-to-only-select-specific-properties-from-an-object-graph-in-entity-framework