GrahamJRoy
GrahamJRoy

Reputation: 1643

Custom Mapping With Automapper Using Global.asax

I have a static mapper class that is called from the Global.asax that can map simple classes fine:

Global.asax:

AutoMapperConfiguration.Configure();

AutoMapperConfiguration:

Configure()
{
  Mapper.Initialize(cfg => { cfg.CreateMap<TMS.Entity.CourseSession, DataAccess.Entities.CourseSession>(); });
  Mapper.Initialize(cfg => {
    cfg.CreateMap<TMS.Entity.Course, DataAccess.Entities.Course>()

where CourseSession is a nested object in Course

public class Course 
{
  public ICollection<CourseSession> CourseSessionColl;

No matter what is seem to do in the mapper it throws an error:

The following property on DataAccess.Entities.CourseSession cannot be mapped: CourseSessionColl

It works if I ignore the property:

Mapper.Initialize(cfg => {
            cfg.CreateMap<TMS.Entity.Course, DataAccess.Entities.Course>()
            .ForMember(o => o.CourseSessionColl, s => s.Ignore())

but if I try to map it it always throws an error.

Edit - Added example of classes

The property in the classes in named the same and also I have the mapping for these preceding that of this map:

namespace TMS.Entity
{
  public class Course
  {
    public ICollection<CourseSession> CourseSessionColl { get; set; }
    ...

------------------------------------------------

namespace DataAccess.Entities
{
  public class Course
  {
    public ICollection<CourseSession> CourseSessionColl { get; set; }

Upvotes: 1

Views: 505

Answers (1)

meJustAndrew
meJustAndrew

Reputation: 6613

The problem is that you are calling the Initialize method twice and the second call overrides the first configuration. You will need to add more maps in the same configuration instead of calling multiple times the Initialize method:

Mapper.Initialize(cfg => { 
cfg.CreateMap<TMS.Entity.CourseSession, DataAccess.Entities.CourseSession>();
cfg.CreateMap<TMS.Entity.Course, DataAccess.Entities.Course>(); });

Upvotes: 1

Related Questions