Asp.net-Mvc

將驗證屬性從域實體映射到 DTO

  • January 15, 2010

我有一個標準的域層實體:

public class Product
{
   public int Id { get; set; }

   public string Name { get; set; }

   public decimal Price { get; set;}
}

它應用了某種驗證屬性:

public class Product
{
   public int Id { get; set; }

   [NotEmpty, NotShorterThan10Characters, NotLongerThan100Characters]
   public string Name { get; set; }

   [NotLessThan0]
   public decimal Price { get; set;}
}

如您所見,我已經完全彌補了這些屬性。這裡使用哪個驗證框架(NHibernate Validator、DataAnnotations、ValidationApplicationBlock、Castle Validator 等)並不重要。

在我的客戶端層中,我也有一個標准設置,我不使用域實體本身,而是將它們映射到我的視圖層使用的 ViewModels(又名 DTO):

public class ProductViewModel
{
   public int Id { get; set; }

   public string Name { get; set; }

   public decimal Price { get; set;}
}

然後假設我希望我的客戶端/視圖能夠執行一些基本的屬性級驗證。

我看到我能做到這一點的唯一方法是在 ViewModel 對像中重複驗證定義:

public class ProductViewModel
{
   public int Id { get; set; }

   // validation attributes copied from Domain entity
   [NotEmpty, NotShorterThan10Characters, NotLongerThan100Characters]
   public string Name { get; set; }

   // validation attributes copied from Domain entity
   [NotLessThan0]
   public decimal Price { get; set;}
}

這顯然不能令人滿意,因為我現在在 ViewModel (DTO) 層中重複了業務邏輯(屬性級驗證)。

那麼可以做些什麼呢?

假設我使用像 AutoMapper 這樣的自動化工具將我的域實體映射到我的 ViewModel DTO,那麼以某種方式將映射屬性的驗證邏輯也傳輸到 ViewModel 不是很酷嗎?

問題是:

1)這是個好主意嗎?

2)如果可以,可以嗎?如果沒有,有什麼替代方案(如果有的話)?

提前感謝您的任何意見!

如果您使用支持 DataAnnotations 的東西,您應該能夠使用元數據類來包含您的驗證屬性:

public class ProductMetadata 
{
   [NotEmpty, NotShorterThan10Characters, NotLongerThan100Characters]
   public string Name { get; set; }

   [NotLessThan0]
   public decimal Price { get; set;}
}

並將其添加到域實體和 DTO 的 MetadataTypeAttribute 中:

[MetadataType(typeof(ProductMetadata))]
public class Product

[MetadataType(typeof(ProductMetadata))]
public class ProductViewModel

這不適用於所有驗證器 - 您可能需要擴展您選擇的驗證框架以實現類似的方法。

引用自:https://stackoverflow.com/questions/2075288