Reputation: 1192
I have 2 classes with exactly the same named attributes (1 business class, and 1 data class).
At this moment i've written a 'convert' method that maps all the attributes van 1 class to the other:
private class BusinessLogic convert(Datalogic dataclass)
{
Businesslogic businessclass = new BusinessLogic();
businessclass.ID = dataclass.ID;
businessclass.name = dataclass.name;
.....
return businessclass;
}
It seems to be that there must be a far more simpler way. I'm only not sure how to search for it. Can someone put me on the right track.
Upvotes: 1
Views: 2557
Reputation: 218832
AutoMapper is a library available which does this Object to Object
mapping for you.
With AutoMapper, Your code can be reduced to some thing like
Mapper.CreateMap<Datalogic , Businesslogic >();
Product product= GetProductFromDB(2);
Businesslogic productViewItem = Mapper.Map<Datalogic , Businesslogic >(product);
Home page: http://automapper.org/
Source: https://github.com/AutoMapper/AutoMapper
Tutorial link http://www.codeproject.com/Articles/61629/AutoMapper
Upvotes: 2
Reputation: 160942
This is a task for a mapping tool, e.g. AutoMapper - if all the properties are named the same this pretty much is a one-line since by convention they will be mapped to the corresponding property in the target class.
For your particular example that could be:
Mapper.CreateMap<Datalogic, BusinessLogic>();
BusinessLogic businessclass = Mapper.Map<Datalogic, BusinessLogic>(dataclass);
Upvotes: 4