We can do validation at model level. The CustomValidation property can do almost everything you want, it is similar than web form's CustomValidation server control. Cool~ The following code shows an example of CustomValidation property.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace JMS.Models
{
public class Auction
{
public long Id { get; set; }
[Required,StringLength(20)]
public string Title { get; set; }
public decimal StartPrice { get; set; }
[CustomValidation(typeof(Auction),"ValidateCurrentPrice")]
public decimal CurrentPrice { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public void SaveNew()
{
using(var context = new JMSDataContext())
{
context.Auctions.Add(this);
context.SaveChanges();
}
}
public static ValidationResult ValidateCurrentPrice(decimal
value, ValidationContext pValidationContext)
{
decimal startPrice = ((Auction)
pValidationContext.ObjectInstance).StartPrice;
if (value <= startPrice)
{
return new ValidationResult("Curret price 必须大于
Start Price", new List<string> { "StartPrice", "CurrentPrice" });
}
return ValidationResult.Success;
}
}
}