1

I have two models, one of which I process and return it to a view and then from the view I send it to a controller. In the controller, I need to send it to a stored procedure but the stored procedure expects a model with different property names. Here is my model:


public class Operator
    {
        public int OPERATOR_OBJECTID { get; set; }

        public string SETTLEMENT_OBJECTID { get; set; }

        public string TECHNOLOGY_OBJECTID { get; set; }
    }

and here is the model the stored procedure expects

public class UploadModel
    {
        public int OPERATOR_OBJECTID { get; set; }
        public string SETTLEMENT_CODE { get; set; }
        public string TECHNOLOGY_CODE { get; set; }
    }

Since I send the properties from Operator, like SETTLEMENT_OBJECTID but it expects SETTLEMENT_CODE it throws an exception. Can I somehow map the properties from one model to another or can I cast one model to another? What would be a good solution here?

Cucko
  • 175
  • 1
  • 16
  • 2
    You can use automapper. See following link https://docs.automapper.org/en/stable/ – viktor.hadomskyi Aug 20 '20 at 08:09
  • 1
    You can also see an example of using AutoMapper [Simple Automapper Example](https://stackoverflow.com/questions/20635534/simple-automapper-example) – viktor.hadomskyi Aug 20 '20 at 08:12
  • Does this answer your question? [Best Practices for mapping one object to another](https://stackoverflow.com/questions/16118085/best-practices-for-mapping-one-object-to-another) – Sinatr Aug 20 '20 at 08:17

1 Answers1

0

As mentioned in the comments, you can use the automapper library and configure as such:

var mapConfig = new MapperConfiguration(
   cfg => cfg.CreateMap<Operator, UploadModel>()
      .ForMember(dest => dest.SETTLEMENT_CODE, opt => opt.MapFrom(src => src.SETTLEMENT_OBJECTID))
      .ForMember(dest => dest.TECHNOLOGY_CODE, opt => opt.MapFrom(src => src.TECHNOLOGY_OBJECTID))
);

Check here the getting started guide: https://docs.automapper.org/en/stable/Getting-started.html

You can also define an explicit operator to be able to cast from one class to the other: https://www.dotnetperls.com/explicit

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61