How to only select specific properties from an object graph in Entity Framework?

前端 未结 1 1527
栀梦
栀梦 2021-01-16 16:21

I have a simple data model

car
 - make
 - model
 - year
 - colour
 - engine
     - model
     - no. cylinders
     - size
     - etc
 - fuel tank
     - mode         


        
相关标签:
1条回答
  • 2021-01-16 16:44

    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.

    0 讨论(0)
提交回复
热议问题