0

我有一個N層應用程序,其中Data,Domain和前端圖層位於不同的項目中。我正在使用ASP.NET MVC創建網站,我試圖通過使用System.ComponentModel.DataAnnotations來添加驗證規則。目前我已經完成了域類的屬性。 我想知道將驗證規則直接應用於Domain類是否是一種好的做法?或者最好在ASP.NET應用程序中創建ViewModels類並將驗證規則應用於ViewModel類的屬性? 希望這個問題適合在這裏 我感謝任何幫助。正確使用ASP.NET MVC應用程序中的DataAnnotations以及單獨項目中的Domain類?

+3

最好創建的ViewModels –

+0

@BrianOgden非常感謝你的幫助。然後我將使用automapper來映射Domain類以查看模型類。如果我可以問,有什麼更好的建議? – arvind

回答

1

ViewModel要好得多,因爲ViewModel應該理解它是否能夠從用戶那裏獲得有效的輸入。然後,您可以使用AutoMapper在轉換過程中修復所有其他異常。我還會創建大量自定義,DataAnnotations,DataTypes,編輯器,ModeMetaDataRules和ModelBinder以與應用程序一起使用。

下面是使用自定義模型構建器的ModelFilter的部分代碼,我將發佈其中的一部分,因爲涉及到很多代碼,但它應該讓您處於正確的軌道上。

public interface IModelMetadataFilter 
    { 
     void TransformMetadata(ModelMetadata metadata, 
      IEnumerable<Attribute> attributes); 
    } 
public class MultilineTextByNameConvention : IModelMetadataFilter 
    { 
     public void TransformMetadata(ModelMetadata metadata, IEnumerable<Attribute> attributes) 
     { 
      if (!string.IsNullOrEmpty(metadata.PropertyName) && 
       string.IsNullOrEmpty(metadata.DataTypeName)) 
      { 
       if (metadata.PropertyName.ToLower().Contains("notes") 
        || metadata.PropertyName.ToLower().Contains("description") 
        || metadata.PropertyName.ToLower().Contains("comment") 
        ) 
       { 
        metadata.DataTypeName = DataType.MultilineText.ToString(); 
       } 
      } 
     } 
    } 

此代碼查找具有包含單詞「註釋」,「說明」和「註釋」,自動應用Multitext數據類型屬性爲所有屬性的屬性名稱每個視圖模型。這種類型的代碼可以用於很多其他不同的情況。例如像SSN這樣的字段可以使用RexExpr DataAnnotation的特定格式,依此類推...

+0

非常感謝您的幫助。我很感激 – arvind

+0

感謝您添加代碼段。您的回答正是我想要的:) – arvind

1

您可以在實體的部分類上設置屬性,並且自動生成的類不會被覆蓋。

例如,

比方說,你有實體TheEntity

用相同的命名空間的單獨的文件,你可以這樣寫:

namespace SameNamespaceAsEntities 
{ 
internal sealed class TheEntityMetadata 
{ 
    //AStringInTheEntity appears twice in your project 
    //once in the auto gen file, and once here 
    [Required(ErrorMessage = "Field is required.")] 
    public string AStringInTheEntity{ get; set; } 
} 

//http://stackoverflow.com/questions/14059455/adding-validation-attributes-with-an-entity-framework-data-model 
[System.ComponentModel.DataAnnotations.MetadataType(typeof(TheEntityMetadata))] 
public partial class TheEntity : IEntity //you can set contracts 
{ 
+0

非常感謝您的幫助 – arvind

+0

@Ssheverdin提供的解決方案出了什麼問題?另外,我不確定我是否瞭解您的建議是誠實的。請詳細解釋我的域名我需要應用數據註釋而不涉及模型類。讓我說我有一個名爲Name的屬性,我想應用[StringLength]。如果另一個項目想要使用我的域項目DLL並且不會需要StringLength限制。因此,Ssheverdin在這裏提供的解決方案聽起來很合理。但我仍然樂於接受建議。直到那時我會尊敬地選擇Ssheverdin解決方案。 – arvind

相關問題