I am new to c# and .NET. I am learning ASP.NET MVC 5. One thing that I am finding myself spending extra time doing in converting a model to a viewmodel.
Here is my model
public class Overview
{
public string chain_name { get; set; }
public int store_id { get; set; }
public int total_attempts { get; set; }
public int total_unique_number_called { get; set; }
public int total_callable { get; set; }
public int total_completed_interviews { get; set; }
}
and here is my view model
public class OverviewViewModel
{
public string chain_name { get; set; }
public int store_id { get; set; }
public int total_attempts { get; set; }
public int total_unique_number_called { get; set; }
public int total_callable { get; set; }
public int total_completed_interviews { get; set; }
public decimal? unique_number_per_complete { get; set; }
public OverviewViewModel()
{
unique_number_per_complete = 0;
}
}
as you can see both Model and ViewModel are identical except for over variable which is a calculation.
To populate my view model I do the following
var records = conn.Database.SqlQuery<Overview>(query).ToList();
var overView = new List<OverviewViewModel>();
foreach(var record in records){
var newRecord = new OverviewViewModel();
newRecord.store_id = record.store_id;
newRecord.chain_name = record.chain_name;
newRecord.total_attempts = record.total_attempts;
newRecord.total_callable = record.total_callable;
newRecord.total_completed_interviews = record.total_completed_interviews;
if (record.total_completed_interviews > 0) {
newRecord.total_unique_number_called = record.total_unique_number_called / record.total_completed_interviews;
}
overView.Add(newRecord);
}
The two issues that I am seeing with my approach is that
Is there an easier way to do this in c#?
Is there a better approach with this procedure for a large application? My goal is to learn the better way to utilize my code time to the fullest.
I agree that you should look into automapper, but another way would be to create a constructor on your OverviewViewModel model that takes and Overview object and populates all the properties. Something like
public class OverviewViewModel {
public string chain_name { get; set; }
public int store_id { get; set; }
public int total_attempts { get; set; }
public int total_unique_number_called { get; set; }
public int total_callable { get; set; }
public int total_completed_interviews { get; set; }
public decimal? unique_number_per_complete { get; set; }
public OverviewViewModel()
{
unique_number_per_complete = 0;
}
public OverviewViewModel(Overview record)
{
store_id = record.store_id;
chain_name = record.chain_name;
total_attempts = record.total_attempts;
total_callable = record.total_callable;
//etc
}
}
Then your code would look like
var overView = new List<OverviewViewModel>();
foreach(var record in records){
overView.Add(new OverViewViewModel(record));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With