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();
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
I found the solution from comment of @AlexanderDerck. ProjectTo method of AutoMapper solve my problem. docs.automapper.org/en/stable/Queryable-Extensions.html
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0