Search code examples
c#fedex

How do I convert (or cast) Fedex shipping request types into rate request types in C#?


So here's the problem: I have written an application to call the Fedex shipping API, but now I also need to make a separate rate request immediately after the shipping request. (The reason is that I need a non-account rate for data and metrics, but I don't get any rates for third-party shipment requests). When I create the rate request, I can do something like this for simple values:

raterequest.RequestedShipment.ServiceType = (rateReference.ServiceType)shiprequest.RequestedShipment.ServiceType;

But I can not do this with any complex types, like this:

raterequest.RequestedShipment.Shipper = (rateReference.Shipper)shiprequest.RequestedShipment.Shipper;

Or even like this:

raterequest.RequestedShipment.Shipper.Address = (rateReference.Address)shiprequest.RequestedShipment.Shipper.Address;

... because .Net will complain that it can't convert between the ship Address type and the rate Address type (though they are identical). I can set the "raterequest" parameters one at a time (i.e. "Address.City"), but it's a hassle AND I eventually want to do something more sophisticated (i.e. call multiple APIs using the same request parameters with minimal additional code). Is there any generic solution to this, so that identical complex types (but in different namespaces) can be converted back and forth?


Solution

  • Automapper is good at this kind of thing. It generally does the "sensible" thing when copying from one type to another, and when it isn't doing the sensible thing (or something nonsensical is required) you can hook that and define what should happen.