簡體   English   中英

將DTO傳遞給我的ViewModels構造函數以映射屬性

[英]Passing DTO to my ViewModels constructor to map properties

在我的解決方案中,我有兩個項目。

項目1(核心)使用Dapper將SQL映射到DTO

項目2(WebUI - ASP.NET MVC 4)這里我使用每個View的ViewModel。

控制器的示例

  [HttpGet]
    public ActionResult Edit(int id)
    {
        // Get my ProductDto in Core
        var product = Using<ProductService>().Single(id);
        var vm = new ProductFormModel(product);

        return View(vm);
    }

ViewModel的示例

public class ProductFormModel : BaseViewModel, ICreateProductCommand
    {
        public int ProductId { get; set; }
        public int ProductGroupId { get; set; }
        public string ArtNo { get; set; }
        public bool IsDefault { get; set; }
        public string Description { get; set; }
        public string Specification { get; set; }
        public string Unit { get; set; }
        public string Account { get; set; }
        public decimal NetPrice { get; set; }

        public ProductFormModel(int productGroupId)
        {
            this.ProductGroupId = productGroupId;
        }

        public ProductFormModel(ProductDto dto)
        {
            this.ProductId = dto.ProductId;
            this.ProductGroupId = dto.ProductGroupId;
            this.ArtNo = dto.ArtNo;
            this.IsDefault = dto.IsDefault;
            this.Description = dto.Description;
            this.Specification = dto.Specification;
            this.Unit = dto.Unit;
            this.Account = dto.Account;
            this.NetPrice = dto.NetPrice;
        }

        public ProductFormModel()
        {
        }
    }

說明:我將使用項目中的服務類(Core)在我的控制器中獲取我的DTO。 然后我創建我的ViewModel並將DTO傳遞給ViewModel中的構造函數。 我也可以使用此視圖添加新產品,因為我的ViewModel可以采用空構造函數。

有沒有人有這方面的經驗。 我想知道如果這個項目越來越大,我將來會遇到這樣的問題嗎?

我知道這與Dapper無關。 但我仍然想要一個解釋我的解決方案的好方法。

我認為使用您當前的方法會很好。 更重要的是,如果您開始遇到與對象映射代碼相關的問題(而不是事先考慮太多),請從這樣開始並重構

我有時使用的組織映射邏輯的另一種方法是使用擴展方法。 這樣,映射代碼與視圖模型本身保持獨立。 就像是:

public static class ProductMappingExtensions
{
    public static ProductFormModel ToViewModel(this ProductDto dto)
    {
        // Mapping code goes here
    }
}

// Usage:

var viewModel = dto.ToViewModel();

另一種方法是使用像AutoMapper這樣的映射框架 - 如果你的映射邏輯很簡單(屬性之間有很多1:1的映射),這是一個很好的選擇。

但是,再次, 在需要時開始簡單和重構

我意識到這是一個有點遲到的答案,但也許它將來會有所幫助。

這種在對象之間進行映射的方式打破了SOLID原則的'S',因為ViewModel的職責是在其屬性中准備數據以供視圖使用,而不是其他任何東西,因此,映射對象不應該在這是責任。

這種方式的另一個缺點是它也打破了'松散耦合'OO原則,因為ViewModel與您的DTO強烈耦合。

我認為,即使我們處於項目的第一步,也有一些重要的OO原則我們永遠不應該破壞,所以使用mapper類,auto(AutoMapper,ValueInjecter ...)或手動,肯定更好。

暫無
暫無

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

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