I have two data provider , they have different data structures. I must to map its structure to myself. I use following code for the aim :
[DataContract]
class Mapper1
{
[DataMember(Name="DataID")]
public int id { get; set; }
[DataMember(Name = "Time")]
public DateTime d_time { get; set; }
}
class Mapper2
{
[DataMember(Name = "ID")]
public int id { get; set; }
[DataMember(Name = "DATE")]
public DateTime d_time { get; set; }
}
I think there's better way to do it. Does anybody know ?
When dealing with different data sources it is often a good idea to have a separation in structure. This will help isolate issues with the different areas of the software when coding. In short, you may want to have better naming conventions for your mappers, and perhaps separate them by namespaces to help distinguish them in the code.
The use of AutoMapper will also help with creating mapping code between the data providers. This way you can focus on the domain language that is appropriate for each provider.
Below is an example that demonstrates using automapper. It uses a bit of code, but in the long run with a large project having the declarative mappings between data types is much cleaner and easier to debug.
namespace Provider1
{
[DataContract]
public class Data
{
[DataMember]
public int DataID { get; set; }
[DataMember]
public DateTime Time { get; set; }
}
}
namespace Provider2
{
[DataContract]
public class Data
{
[DataMember]
public int ID { get; set; }
[DataMember]
public DateTime DATE { get; set; }
}
}
namespace Internal
{
public class Data
{
public int id { get; set; }
public DateTime d_time { get; set; }
}
}
public static class Configuration
{
public static void InitMappers()
{
AutoMapper.Mapper.CreateMap<Internal.Data, Provider1.Data>()
.ForMember(x=> x.DataID, opt=> opt.MapFrom(src=> src.id))
.ForMember(x=> x.Time, opt=> opt.MapFrom(src => src.d_time));
AutoMapper.Mapper.CreateMap<Internal.Data, Provider2.Data> ()
.ForMember (x => x.ID, opt => opt.MapFrom (src => src.id))
.ForMember (x => x.DATE, opt => opt.MapFrom (src => src.d_time));
}
}
public class TestExample
{
public void Test()
{
var src = new Internal.Data ();
var dest = AutoMapper.Mapper.Map<Provider1.Data> (src);
var dest2 = AutoMapper.Mapper.Map<Provider2.Data> (dest);
}
}