'How to fix error "Error mapping types" in AutoMapper?
I have these two classes which were reverse engineered (scaffolded) with EF Core:
public partial class TblA
{
public TblA()
{
TblBs = new HashSet<TblB>();
}
public string TenantId { get; set; }
public int Id { get; set; }
public virtual ICollection<TblB> TblBs { get; set; }
}
public partial class TblB
{
public string TenantId { get; set; }
public int Id { get; set; }
public string Value { get; set; }
public virtual TblA A { get; set; }
}
Now, I am trying to use AutoMapper to map an object of class TblA into an object of class A. This is how class A is defined in my project:
public class A
{
public string TenantId { get; set; }
public int? Id { get; set; }
public List<B> Bs { get; set; }
}
public class B
{
public string TenantId { get; set; }
public int Id { get; set; }
public string Value { get; set; }
}
This is how my map is defined:
CreateMap<TblA, A>()
.ForMember(dest => dest.Bs, opt => opt.MapFrom(src => src.TblBs))
.ReverseMap()
In my project, I am creating an object of class TblA which I then add to the database via AddAsync() and SaveChangesAsync(). Then, I try to map this object to class A via Map<A>(entity) where entity is the object which I also passed to AddAsync().
Right after calling Map<A>(entity), I get this error:
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
AutoMapper.AutoMapperMappingException: Error mapping types.
Mapping types:
TblA -> A
<namespace>.TblA -> <namespace>.A
Type Map configuration:
TblA -> A
<namespace>.TblA -> <namespace>.A
Destination Member:
Bs
---> AutoMapper.AutoMapperMappingException: Error mapping types.
Mapping types:
TblB -> B
<namespace>.TblB -> <namespace>.B
Type Map configuration:
TblB -> B
<namespace>.TblB -> <namespace>.B
Destination Member:
TenantId
---> System.NullReferenceException: Object reference not set to an instance of an object.
at lambda_method734....
I have thoroughly inspected the object before mapping it and the TenantId is set just fine to a valid string value. Therefore, I do not understand where this error is coming from because the TenantId is not null. What could be the problem here?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
