我是新來的c#和.NET。我正在學習ASP.NET MVC 5.我發現自己花費額外的時間將模型轉換爲視圖模型。是否有將模型轉換爲視圖模型的快捷方式?
這裏是我的模型
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; }
}
,這裏是我的視圖模型
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;
}
}
,你可以看到兩個模型和視圖模型是相同的,除了以上變量,它是一個計算。
要填充我的視圖模型我下面
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);
}
,我用我的方法看到的兩個問題是,
- 我必須做很多額外的編碼尤其是考慮到模型是大的或f我有多個變量,我需要計算。
- 我覺得我循環1額外的時間將我的模型轉換爲視圖模式。
在c#中有更簡單的方法嗎?
對於大型應用程序,此過程有更好的方法嗎?我的目標是要學習更好的方式來充分利用我的代碼時間。
AutoMapper可以幫助簡單映射。 – user2864740
請注意,Automapper是非常慢,如果你有大量的數據tp過程,想想自己的自定義映射器[鏈接] http://stackoverflow.com/questions/4131720/automapper-running-extremely-slow-on-mapping -1400-records – Thakur