How to map User class to UserModel class using Emit Mapper?
public class User
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public IList<Role> Roles { get; set; }
public Company Company { get; set; }
}
public class UserModel
{
public Guid Id { get; set; }
public Guid CompanyId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public IList<RoleModel> Roles { get; set; }
}
There several problems:
List<Role>
to List<RoleModel>
For flattering I was using configuration from the samples in Emit Mapper source files: http://emitmapper.codeplex.com/SourceControl/changeset/view/69894#1192663
To make the names to match in Company class should be the field with the name Id
For mapping List<Role>
to List<RoleModel>
I was using custom converter:
public class EntityListToModelListConverter<TEntity, TModel>
{
public List<TModel> Convert(IList<TEntity> from, object state)
{
if (from == null)
return null;
var models = new List<TModel>();
var mapper = ObjectMapperManager.DefaultInstance.GetMapper<TEntity, TModel>();
for (int i = 0; i < from.Count(); i++)
{
models.Add(mapper.Map(from.ElementAt(i)));
}
return models;
}
}
So all together:
var userMapper = ObjectMapperManager.DefaultInstance.GetMapper<User, UserModel>(
new FlatteringConfig().ConvertGeneric(typeof(IList<>), typeof(IList<>),
new DefaultCustomConverterProvider(typeof(EntityListToModelListConverter<,>))));
There is a problem, using Flatterning Configuration with Custom converters, check my question: Emit Mapper Flattering with Custom Converters