I am using MVVM here. I have one model Patient.cs
and 3 view models ViewModel1
, ViewModel2
, ViewModel3
. I now have to convert 3 view models into one model.
Can someone please let me know the best way to do it. Below is my code:
ViewModel1.cs
public class ViewModel1 {
[Required]
public string? YearOfBirth { get; set; }
[Required]
public string? DriversLicenseId { get; set; }
}
ViewModel2.cs
public class ViewModel2
{
[Required]
[StringLength(16, ErrorMessage = "First name should be 16 character or less.")]
public string? FirstName { get; set; }
[Required]
[StringLength(16, ErrorMessage = "Last name should be 16 character or less.")]
public string? LastName { get; set; }
[Required]
public DateTime? DateOfBirth { get; set; }
}
ViewModel3.cs
public class ViewModel3
{
[Required]
public string? Address1 { get; set; }
[Required]
public string? City { get; set; }
[Required]
public string? State { get; set; }
[Required]
public string? ZipCode { get; set; }
}
Model Patient.cs
public class Patient
{
public string? FirstName { get; set; }
public string? LastName { get; set; }
public DateTime? DateOfBirth { get; set; }
public Gender? Gender { get; set; }
public string? YearOfBirth { get; set; }
public string? DriversLicenseId { get; set; }
public string? Address1 { get; set; }
public string? City { get; set; }
public string? State { get; set; }
public string? ZipCode { get; set; }
public string? PaymentType { get; set; }
}
I'm looking for some way to convert all the three view models to Patient.cs
Thanks.
CodePudding user response:
You don't use to repeat the variables
Patient.cs
public class Patient
{
// Constructor
public Patient()
{
_viewModel1 = new ViewModel1();
_viewModel2 = new ViewModel2();
_viewModel3 = new ViewModel3();
}
public ViewModel1 _viewModel1 { get; set; }
public ViewModel2 _viewModel2 { get; set; }
public ViewModel3 _viewModel3 { get; set; }
}
CodePudding user response:
Create Constructor in Patient Class and Create New Models Example :
public class Patient
{
// Constructor
public Patient()
{
//you need create new models in Constructor
viewModel1 = new ViewModel1();
viewModel2 = new ViewModel2();
viewModel3 = new ViewModel3();
}
public ViewModel1 viewModel1 { get; set; }
public ViewModel2 viewModel2 { get; set; }
public ViewModel3 viewModel3 { get; set; }
}