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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.