DOTang DOTang - 1 month ago 20
C# Question

Automapper says Missing map from System.String to System.Char? But I see no Char property

I've got three classes:

public class UserReport : Entity
{
public string Name { get; set; }
public string Email { get; set; }
public List<string> Departments { get; set; }
public List<string> Titles { get; set; }
}

public abstract class Entity
{
public Guid Id { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateLastModified { get; set; }
public string CreatedBy { get; set; }
public string LastModifiedBy { get; set; }
public bool Active { get; set; }

protected Entity()
{
DateCreated = DateTime.Now;
DateLastModified = DateTime.Now;
Id = Guid.NewGuid();
}
}

public class UserModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Departments { get; set; }
public string Titles { get; set; }
}


With my automapper configs set as:

CreateMap<List<string>, string>().ConvertUsing(strings => {
if (strings != null)
return string.Join("\n", strings);
return "";
});
CreateMap<UserReport, UserModel>();


When trying to call from a generic method using the Automapper Ef Extensions:

IQueryable<TModel> modelQueryable = _reportService.GetReportBaseQuery().ProjectToQueryable<TModel>();


I get this error


Missing map from System.String to System.Char. Create using Mapper.CreateMap.


GetReportBaseQuery()
returns an
IQueryable<TReport>
, so the
UserReport
in this instance. I don't see any
char
properties, why is this coming up?

Just for testing I tried to make one:

CreateMap<String, Char>().ConvertUsing(x => x.FirstOrDefault());


And then it says:


Argument types do not match


Further research shows that this works:

Mapper.Map<List<TReport>, List<TModel>>(_reportService.GetReportBaseQuery().ToList());


But I can't use that since I need it to be a queryable returned. So something is different when I try to do an EF projection, not sure what that is though. Writing a select statement from one to the other is easy enough, but that's not generic and re-usable.

Answer

The solution is to explicitly set mapping for the Departments and Titles fields:

CreateMap<UserReport, UserModel>()
    .ForMember(x => x.Departments, o => o.MapFrom(s => string.Join("\n", s.Departments)))
    .ForMember(x => x.Titles, o => o.MapFrom(s => string.Join("\n", s.Titles)));

But, this does not explain, why this situation occurs. As DOTang pointed out:

LINQ to Entities does not recognize the method 'System.String Join(System.String, System.Collections.Generic.IEnumerable1[System.String])' method, and this method cannot be translated into a store expression.

The AutoMapper extension seems to try to map the following thing:

IEnumerable<string> => IEnumerable<char>