I have a simple data model
car
- make
- model
- year
- colour
- engine
- model
- no. cylinders
- size
- etc
- fuel tank
- mode
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.