2011-01-29 72 views
1

假設我有一個值對象類FullName,它用作Employee實體類中的一個屬性。 FullName可能有中間名,暱稱等;但從域的角度來看,我只想強調FullName的FirstName和LastName屬性是重要的。nhibernate驗證器用法

我想將其表示爲EmployeeValidator的一部分:ValidationDef {Employee}對象,而不是屬性。

我是否首先需要爲FullName(即FirstAndLAstNameRequired)創建一個類驗證程序,然後說Employee中的FullName屬性是Valid(使用一些Loquacious形式的ValidAttribute)?

順便說一句,看起來this documentation仍然是最好的,但它確實看起來過了三歲。我錯過了更新的東西嗎?

乾杯,
Berryl

UPDATE

我還沒有想通了這一點,但我發現什麼是可能在這裏NHib驗證信息的最佳來源:http://fabiomaulo.blogspot.com/search/label/Validator

這裏是一些僞代碼來表達更好的問題:

/// <summary>A person's name.</summary> 
public class FullName 
{ 

    public virtual string FirstName { get; set; } 
    public virtual string LastName { get; set; } 
    public virtual string MiddleName { get; set; } 
    public virtual string NickName { get; set; } 
} 

public class EmployeeValidator : ValidationDef<Employee> 
{ 
    public EmployeeValidator() 
    { 
     Define(x => x.FullName).FirstAndLastNameRequired(); // how to get here!! 
    } 
} 

UPDATE FOR DAV ID

public class FullNameValidator : ValidationDef<FullName> 
{ 
    public FullNameValidator() { 

     Define(n => n.FirstName).NotNullable().And.NotEmpty().And.MaxLength(25); 
     Define(n => n.LastName).NotNullable().And.NotEmpty().And.MaxLength(35); 

     // not really necessary but cool that you can do this 
     ValidateInstance 
      .By(
       (name, context) => !name.FirstName.IsNullOrEmptyAfterTrim() && !name.LastName.IsNullOrEmptyAfterTrim()) 
      .WithMessage("Both a First and Last Name are required"); 
    } 
} 

public class EmployeeValidator : ValidationDef<Employee> 
{ 
    public EmployeeValidator() 
    { 
     Define(x => x.FullName).IsValid(); // *** doesn't compile !!! 
    } 
} 

回答

1

要得到驗證的全名時,驗證員工,我想你會做類似如下:

public class EmployeeValidator : ValidationDef<Employee> 
{ 
    public EmployeeValidator() 
    { 
     Define(x => x.FullName).IsValid(); 
     Define(x => x.FullName).NotNullable(); // Not sure if you need this 
    } 
} 

然後全名驗證只會是這樣的:

public class FullNameValidator : ValidationDef<FullName> 
{ 
    public EmployeeValidator() 
    { 
     Define(x => x.FirstName).NotNullable(); 
     Define(x => x.LastName).NotNullable(); 
    } 
} 

或者我認爲你可以做類似的事情(沒有檢查句法):

public class EmployeeValidator: ValidationDef<Employee> 
{ 
public EmployeeValidator() { 

    ValidateInstance.By((employee, context) => { 
     bool isValid = true; 
     if (string.IsNullOrEmpty(employee.FullName.FirstName)) { 
      isValid = false; 
      context.AddInvalid<Employee, string>(
       "Please enter a first name.", c => c.FullName.FirstName); 
     } // Similar for last name 
     return isValid; 
    }); 
} 
} 
+0

我同意你的觀點,基本上,除了你的第一行不能編譯(儘管看起來只是需要的東西)。請參閱發佈的最新更新。 – Berryl 2011-01-30 16:21:36