2013-08-21 102 views
7

我開發ASP.NET應用程序MVC4,EF代碼第一。 我有基類:不同DataAnnotation屬性派生類

public class Entity 
    { 
     public int Id { get; set; } 
     public string Title { get; set; } 
    } 

,我有一些派生類,例如:

public class City : Entity 
{ 
    public int Population { get; set; } 
} 

等衆多派生類(文,主題,汽車等)。現在我想爲所有類中的Title屬性實現「Required」屬性,並且我希望對於不同的派生類有不同的ErrorMessages。例如,題目類別的「標題不能爲空」,「爲汽車類別命名您的汽車」等。我該怎麼做?謝謝!

回答

11

你可以做財產在基類的虛:

public class Entity 
{ 
    public int Id { get; set; } 
    public virtual string Title { get; set; } 
} 

,然後重寫它的子類,使之所需,並指定你想顯示錯誤消息:

public class City : Entity 
{ 
    public int Population { get; set; } 

    [Required(ErrorMessage = "Please name your city")] 
    public override string Title 
    { 
     get { return base.Title; } 
     set { base.Title = value; } 
    } 
} 

另外,您可以使用FluentValidation.NET,而不是數據註釋來定義您的驗證邏輯,在這種情況下,你可能有不同的具體類型不同的驗證。例如:

public class CityValidator: AbstractValidator<City> 
{ 
    public CityValidator() 
    { 
     this 
      .RuleFor(x => x.Title) 
      .NotEmpty() 
      .WithMessage("Please name your city"); 
    } 
} 

public class CarValidator: AbstractValidator<Car> 
{ 
    public CityValidator() 
    { 
        this 
            .RuleFor(x => x.Title) 
            .NotEmpty() 
            .WithMessage("You should specify a name for your car"); 
    } 
} 

... 
+0

虛擬/替換選項,有利於我的申請。這是我需要的。謝謝! – ifeelgood

+0

當您在基類中定義一個屬性時,它應該被所有派生類使用。 – Jowen

+0

通過在基類中使屬性變爲虛擬,Range校驗器在子類中聲明。 – BrainCoder