Sunday 30 April 2017

C# AutoMapper.Mapper does not contain definition for CreateMap

public ClientEntity GetById(int id)
          {
                 ClientEntity returnClientEntity = new ClientEntity();
                 try
                 {
                        using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted }))
                        {
                               using (DBContext context = new DBContext())
                               {

                                      //Get data based on  id                 
                                      var clientInfoDB = context.Clientinfoes.Where(s => s.ClientID == id).FirstOrDefault();

                                      if (clientInfoDB != null)
                                      {

                                             ////I tried below line first
                                             //returnClientEntity = clientInfoDB;
                                             //return clientInfoDB;// get error


                                             //Problem: clientInfoDB is DB object, but method is returning entity object which is not ClientEntity
                                             //So need mapping b/w DB and entity

                                             //Solution--start
                                             var config = new MapperConfiguration(cfg => {
                                                   cfg.CreateMap<Clientinfo, ClientEntity>();
                                             });

                                             IMapper mapper = config.CreateMapper();
//below line is mapping b/w DB and entity
                                             returnClientEntity = mapper.Map<Clientinfo, ClientEntity>(clientInfoDB);
                                             //end
                                      }
                                      else
                                      {
                                             return null;
                                      }
                               }
                        }
                 }
                 catch (Exception ex)
                 {

                 }
                 return returnClientEntity;

              }