This repository has been archived by the owner on Apr 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Conversion between ViewModel and Data Transfer Object
David Sungaila edited this page Sep 18, 2020
·
1 revision
Make sure that any property you wish to convert is public
(both getter and setter) in your DTO class.
// C# code of DTO class
public class AwesomeTransferDataObject
{
public string PersonName { get; set; }
public int PersonAge { get; set; }
}
Mark your ViewModel with the DtoAttribute
and use the DTO Type
.
Now mark any property you wish to be converted with DtoPropertyAttribute
. If both DTO and ViewModel property names are identical, you can omit the propertyName
parameter.
// C# code of your ViewModel class
[Dto(typeof(AwesomeTransferDataObject))]
public class AwesomeViewModel : ViewModel
{
private string _name;
[DtoProperty]
public string Name
{
get => _name;
set => SetProperty(ref _name, value);
}
private int _age;
[DtoProperty]
public int Age
{
get => _age;
set => SetProperty(ref _age, value);
}
}
Here is an example how conversion can be applied:
// C# code of the conversion
var dto = new AwesomeTransferDataObject { PersonName = "John" };
var viewModel = dto.ToViewModel<AwesomeViewModel>();
if (viewModel.Name == "John")
viewModel.Age = 33;
var dto2 = viewModel.ToDto<AwesomeTransferDataObject>();