realist
realist

Reputation: 2375

Getting only some columns in DTO class from table by Entity Framework

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?

My DTO class:

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();

Upvotes: 0

Views: 2030

Answers (2)

realist
realist

Reputation: 2375

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

Upvotes: 1

Scott Bennington
Scott Bennington

Reputation: 44

Have you tried Automapper? As long as the names of the properties in your DTO match the ones in the EF context, you're good to do. And as you add properties to your DTO, they would automatically be translated.

If the names/types don't match between the DTO and EF context, there may need to be additional configuration in your mapper profile.

Here is a simplified example.

 class Program
{
    static void Main(string[] args)
    {
        var mapperConfiguration = new MapperConfiguration(cfg => cfg.AddProfile<MappingProfile>());
        var mapper = mapperConfiguration.CreateMapper();

        var fullStudent = new FullStudent()
        {
            Name = "Mike",
            Surname = "Magoo",
            BirthDate = DateTime.Now,
            StudentNumber = 1,
            Grade = "Freshman",
            PhoneNumber = "555-5555"
        };

        var limitedStudent = mapper.Map<StudentDTO>(fullStudent);

        Console.ReadKey();
    }
}

public class FullStudent
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public DateTime BirthDate { get; set; }
    public int StudentNumber { get; set; }

    public string Grade { get; set; }

    public string PhoneNumber { get; set; }
}

public class StudentDTO
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public DateTime BirthDate { get; set; }
    public int StudentNumber { get; set; }
}

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<FullStudent, StudentDTO>();
    }
}

Automapper can be installed as a nuget package.

Upvotes: 1

Related Questions