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 nested ViewModel and Data Transfer Object
David Sungaila edited this page Sep 18, 2020
·
1 revision
Conversion is for nested ViewModels is possible. Your DTO must use a property type that inherits IList
and has a parameterless constructor.
// C# code of DTO class
public class NestedTransferDataObject
{
public string Name { get; set; }
public List<NestedTransferDataObject> Others { get; set; }
}
The ViewModel property type must be (or derived from) ObservableViewModelCollection<>
.
// C# code of your ViewModel class
[Dto(typeof(NestedTransferDataObject))]
public class NestedViewModel : ViewModel
{
private string _name;
[DtoProperty]
public string Name
{
get => _name;
set => SetProperty(ref _name, value);
}
[DtoProperty]
public ObservableViewModelCollection<NestedViewModel> Others { get; }
public NestedViewModel()
{
Others = new ObservableViewModelCollection<NestedViewModel>(this);
}
}
If those requirements are met, you can execute the following conversion just fine:
// C# code of the conversion
var dto = new NestedTransferDataObject
{
Name = "Timmy",
Others = new List<NestedTransferDataObject>(new[] {
new NestedTransferDataObject { PersonName = "Bobby" }
})
};
var viewModel = dto.ToViewModel<NestedViewModel>();
if (viewModel.Others.Single().Name == "Bobby")
viewModel.Name = "Definitely not Timmy";
var dto2 = viewModel.ToDto<NestedTransferDataObject>();