C# Automapper Ignore methods ProjectTo<TModel>()

Viewed 187

How can I ignore public methods in my entity class while automapping using ProjectTo<TModel>().

var query = userRepository.GetQuery<UserViewModel>()
        .OrderBy(x => x.First_name).AsQueryable();

cfg.CreateMap<AspNetUser, UserViewModel>(MemberList.None);
// Cannot add method to ignore here

Its giving this error:

on function return query.ProjectTo<TModel>(); 'Member 'System.String GetFullName()' not field or property'

public virtual IQueryable<TModel> GetQuery<TModel>(Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null)
{
    IQueryable<TEntity> query = DbSet;

    if (filter != null)
        query = query.Where(filter);

    if (orderBy != null)
        return orderBy(query).ProjectTo<TModel>();
    
    return query.ProjectTo<TModel>();
}

My Entity Class :

public AspNetUser()
{
    public string Id { get; set; }      
    public string First_name { get; set; }
    public string Middle_name { get; set; }
    public string Last_name { get; set; }

    public string GetFullName()
    {
        return string.Join(" ", new[] { First_name, Middle_name, Last_name }.Where(c => !string.IsNullOrEmpty(c)));
    }
}
1 Answers

I think you should not ProjectTo cause of:

Preventing lazy loading/SELECT N+1 problems
Because the LINQ projection built by AutoMapper is translated directly to a SQL query by the query provider, the mapping occurs at the SQL/ADO.NET level, and not touching your entities. All data is eagerly fetched and loaded into your DTOs.

https://docs.automapper.org/en/stable/Queryable-Extensions.html

I think GetFullName() is not available on IQueryable. Queryable means you building a query to be executed on SQL Server. And GetFullName() is not executable on SQL Server.

  1. You should filter you query

  2. Use .ToList()

  3. use Automapper like that :

    _mapper.Map<CalendarEvent, CalendarEventForm>(calendarEvent);
    

You can map Lists also

_mapper.Map<List<UserModel>>
_mapper.Map<List<UserModel>, List<UserEntity>>

I hope that this helps you.

Related