Huy Trương Huy Trương - 3 months ago 133
C# Question

Automapper complex entity c#

My entity

public partial class Users
{
public Users()
{
sexs = new HashSet<Ta>();
}
[BsonElement("_id")]
[BsonId]
public ObjectId UserID { get; set; }
public string username { get; set; }
public string email { get; set; }
public virtual ICollection<Ta> sexs { get; set; }
}
public partial class Ta
{
public string male { get; set; }
public string female { get; set; }
}


public class TEntity
{
public string male { get; set; }
public string female { get; set; }
}

public class UsersEntity
{

public ObjectId UserID { get; set; }
public string email { get; set; }
public virtual ICollection<TEntity> sexs { get; set; }
public string username { get; set; }

}


And my Services:

public void Insert(UsersEntity student)
{
Mapper.Initialize(cfg => cfg.CreateMap<TEntity, Ta>());
Mapper.Initialize(cfg => cfg.CreateMap<UsersEntity, Users().ForMember(c => c.sexs,o => o.MapFrom(s =>s.sexs)));

var a = Mapper.Map<UsersEntity, Users>(student);

_unitOfwork.UsersRepo.Add(a);

}


I failed in

var a = Mapper.Map<UsersEntity, Users>(student);


An exception of type 'AutoMapper.AutoMapperMappingException' occurred in AutoMapper.dll but was not handled in user code

Additional information: Error mapping types.

I use AutoMapper 5.1.1 , Visual Studio 2015 and MongoDB

Please help me!! Thank you!

Answer

You can only call Mapper.Initialize once. Each call to Initialize, starts with a call to Mapper.Reset() first. Try C#

Mapper.Initialize(cfg => {
            cfg.CreateMap<TEntity, Ta>();
            cfg.CreateMap<UsersEntity, Users>().ForMember(c => c.sexs, o => o.MapFrom(s => s.sexs));
            });

instead of two calls.

Comments