簡體   English   中英

Automapper -> DTO 到實體 - 映射時如何觸發 Setter 驗證

[英]Automapper -> DTO to Entity - How to trigger Setter validations when mapping

我創建了一個域實體,所有設置方法都是私有的,因為它們在設置數據之前有一些驗證。

所以我有 Dtos 來交換數據,然后我將 map 發送到實體,所以如果一切順利,我可以持久保存到數據庫。

將 Dto 映射到 Entity 時,我得到了填充了所有屬性的 Entity,但沒有執行 SetXXX,因為如果我直接調用構造函數會發生這種情況。

使用 AutoMapper 時,對於這些情況,最好或正確的方法是什么?

域實體

public Product(Guid id, ... decimal originalPrice, decimal discountedPrice...) :
            base(id)
        {
            OriginalPrice = CheckOriginalPrice(originalPrice, discountedPrice);
            DiscountedPrice = CheckDiscountedPrice(originalPrice, discountedPrice);
        }

        public virtual void SetOriginalPrice(decimal originalPrice, decimal discountedPrice)
        {
            OriginalPrice = CheckOriginalPrice(originalPrice, discountedPrice);
        }

private static decimal CheckOriginalPrice(decimal originalPrice, decimal discountedPrice)
        {
            if (originalPrice < 0)
                throw new ArgumentOutOfRangeException($"original price ({originalPrice} cannot be negative");
            else if (originalPrice < discountedPrice)
                throw new ArgumentOutOfRangeException($"original price ({originalPrice}) can not be lower than discounted price ({discountedPrice})!");

            return originalPrice;
        }

如果我這樣做,Map 會成功,所以沒有驗證發生,如何觸發構造函數?

var product = _objectMapper.Map<CreateProductDto, Product>(product);

如果我直接測試實體 class 它會通過測試,因為檢查了價格並且我得到了異常。

var exception = await Assert.ThrowsAsync<ArgumentOutOfRangeException>(async () =>
            {
                //Act
                var product =
                    new Product(
                        _guidGenerator.Create(),
                        ...
                        4.05m,
                        8.05m,
                        ...
                    );
            });
            //Assert
            exception.Message.ShouldContain("original price");

那么,當使用 ObjetMapper.Map 進行映射時,如何實現該構造函數將正確執行,有沒有簡單的方法來完成它?

AutoMapper 有一個稱為條件映射的功能,這似乎是您正在尋找的: https://docs.automapper.org/en/stable/Conditional-mapping.html

實際上,我設法通過使用與我的 dto 具有相同參數的構造函數來解決我的問題,這樣 AutoMapper 可以直接使用正確的構造函數。

暫無
暫無

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

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