簡體   English   中英

我們可以在c#asp.net mvc app中使用靜態方法將DB對象設置為VIewModel對象嗎

[英]Can we have static method to set DB object to VIewModel object in c# asp.net mvc app

我在我的項目中使用 Asp.Net MVC、C#、EF 6 CodeFirst。 在某些視圖中,我需要來自多個實體的顯示屬性,為此我創建了 ViewModel。 現在將 ViewModel 映射到模型(數據庫對象)而不是使用 AutoMapper(對象映射器),我正在嘗試實現我自己的方式。 在 ViewModel 類中,我創建了名為 GetViewModel() 的靜態方法,並將對象從模型映射到視圖模型。 我可以這樣用嗎。 它對性能有好處還是會產生任何問題。 既然是網絡應用程序。?

public class CustomerViewModel
{       
    public int CustomerId { get; set; }    
    public string CustomerName { get; set; }    
    public string Locations{ get; set; }  

    public static CustomerViewModel GetCustomerWithFullAddress(Customer customer)
    {
        try
        {
            CustomerViewModel viewModel = new CustomerViewModel();
            viewModel.CustomerId = customer.CustomerId;
            viewModel.CustomerName = customer.CustomerName;
            foreach(Address address in customer.Addresses){ 
                viewModel.Locations = viewModel.Locations +"," + address.Country;                                                
            }
            return viewModel;
        }
        catch (Exception ex)
        {                
            throw ex;
        }
    }

}

然后在控制器中我可以這樣訪問。

 Customer customer= db.Customer.Where(x => x.CustomerId == 1).FirstOrDefault();
 CustomerViewModel response = CustomerViewModel.GetViewModel(customer);

AutoMapper 並不慢,假設映射的定義在構造函數中,這在初始化類的調用中發生一次。 您可以嘗試添加一個秒表來記錄要跟蹤的時間,以真正確定它是否“太慢”。

這是將模型映射到視圖模型的絕佳方式。 所以繼續使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM