1

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 !

AGH
  • 353
  • 1
  • 14

1 Answers1

1

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

devendra
  • 79
  • 2
  • I accepted that it will map automatically if property names are the same but this is not my question answer. – AGH Aug 19 '19 at 09:47
  • Not sure what issue you are facing. Please refer this link: http://docs.automapper.org/en/stable/Queryable-Extensions.html – devendra Aug 19 '19 at 16:33
  • Sorry, i could not explain well and i have update my question. – AGH Aug 20 '19 at 08:10