是否有将模型转换为视图模型的快捷方式?

Jun*_*ior 4 .net c# asp.net asp.net-mvc asp.net-mvc-5

我是 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; }

}
Run Code Online (Sandbox Code Playgroud)

这是我的视图模型

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,除了作为计算的过度变量之外,模型和视图模型都是相同的。

要填充我的视图模型,我执行以下操作

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);
}
Run Code Online (Sandbox Code Playgroud)

我在我的方法中看到的两个问题是

  1. 我必须做很多额外的编码,尤其是视图模型很大或者我有多个需要计算的变量。
  2. 我觉得我要循环 1 次额外的时间来将我的模型转换为查看模式。

在 C# 中是否有更简单的方法来做到这一点?

对于大型应用程序,此过程是否有更好的方法?我的目标是学习更好的方法来充分利用我的代码时间。

eto*_*bot 5

我同意你应该研究 automapper,但另一种方法是在你的 OverviewViewModel 模型上创建一个构造函数,它接受和概述对象并填充所有属性。就像是

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
    }
}  
Run Code Online (Sandbox Code Playgroud)

然后你的代码看起来像

var overView = new List<OverviewViewModel>();

foreach(var record in records){
    overView.Add(new OverViewViewModel(record));
}
Run Code Online (Sandbox Code Playgroud)