如何仅从实体框架中的对象图中选择特定属性? [英] How to only select specific properties from an object graph in Entity Framework?

查看:37
本文介绍了如何仅从实体框架中的对象图中选择特定属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的数据模型

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/ 使用选择进入匿名类,但不能看看这如何在多个包含中工作 ]

[ 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.

这篇关于如何仅从实体框架中的对象图中选择特定属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆