通过实体框架仅从表中获取DTO类中的某些列 [英] Getting only some columns in DTO class from table by Entity Framework

查看:104
本文介绍了通过实体框架仅从表中获取DTO类中的某些列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有C#的实体框架.我的数据库中有一个Student表,它有 30列.而且我只想获取DTO类中的表的某些列,而无需编写属性名称,如下所示.我该如何实现?

I'm using Entity Framework with C#. I have a Student table in my database and it has 30 columns. And I want to getting only some columns of table which are in DTO class without writing property names like below. How can I achieve this?

我的DTO课程:

public class StudentDTO()
{
    public long Name{ get; set; }
    public long Surname{ get; set; }
    public DateTime BirthDate{ get; set; }
    public int StudentNumber{ get; set; }
}

我正在寻找这样的东西:

I'm looking for something like this:

context.Students.Select(p=> new StudentDTO
{
  ????? StudentDTO.AllProperties  ?????
}).ToList();

请不要在解决方案下方提出建议,因为这不是我想要的.

Please don't advice below solution, because this is not what I'm looking for.

context.Students.Select(p => new 
                             {
                                 p.Name,
                                 p.Surname,
                                 p.BirthDate,
                                 p.StudentNumber
                             }).ToList();

推荐答案

我从@AlexanderDerck的评论中找到了解决方案. AutoMapperProjectTo方法解决了我的问题. docs.automapper.org/en/stable/Queryable-Extensions.html

I found the solution from comment of @AlexanderDerck. ProjectTo method of AutoMapper solve my problem. docs.automapper.org/en/stable/Queryable-Extensions.html

这篇关于通过实体框架仅从表中获取DTO类中的某些列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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