Want to select specific column through AutoMapper

1k Views Asked by At

Say we have a User entity with the following declaration:

public class User
{
public string About { get; set; }
public string FirstName { get; set; }
public int Id { get; set; }
public string LastName { get; set; }
public string ProfileImageUrl { get; set; }
}

Configure AutoMapper:

using AutoMapper;
// ...
Mapper.CreateMap<User, UserSummary>();

Since the property names of the two classes match, there is no need for further configurations.

Now i am converting this query

using (var context = new ApplicationContext())
{
var users = context.Users.ToList();
}

with this using auto mapper, its work perfect.

using AutoMapper.QueryableExtensions;
using System.Linq;
using (var context = new ApplicationContext())
{
var users = context.Users
                    .Project()
                    .To<UserSummary>()
                    .ToList();
}

The resulting SQL query is:

SELECT
[Extent1].[Id] AS [Id],
[Extent1].[About] AS [About],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName],
[Extent1].[ProfileImageUrl] AS [ProfileImageUrl]
FROM [dbo].[Users] AS [Extent1]
go

Now how do i select specific column instead of all column using auto mapper ?

I can do like this but it does not make sense.

using (var context = new ApplicationContext())
{
 var users = context.Users
                    .Select(u => new UserSummary
                    {
                        FirstName = u.FirstName,
                        LastName = u.LastName,
                        ProfileImageUrl = u.ProfileImageUrl
                    })
                    .ToList();

}

Thanks you in advance !

1

There are 1 best solutions below

3
devendra On

If StateName is the property name in StateMaster and StateMasterDTO classes, .ForMember() isn't required as AutoMapper is smart enough to map it automatically.