ASP.NET MVC 4, EF5, Unique property in model - best practice?

前端 未结 7 518
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 07:24

ASP.NET MVC 4, EF5, Code First, SQL Server 2012 Express

What is best practice to enforce a unique value in a model? I have a places class that has a

相关标签:
7条回答
  • 2020-12-13 08:01

    I solved the general problem of enabling constructor injection in your Validation flow, integrating into the normal DataAnnotations mechanism without resorting to frameworks in this answer, enabling one to write:

    class MyModel 
    {
        ...
        [Required, StringLength(42)]
        [ValidatorService(typeof(MyDiDependentValidator), ErrorMessage = "It's simply unacceptable")]
        public string MyProperty { get; set; }
        ....
    }
    
    public class MyDiDependentValidator : Validator<MyModel>
    {
        readonly IUnitOfWork _iLoveWrappingStuff;
    
        public MyDiDependentValidator(IUnitOfWork iLoveWrappingStuff)
        {
            _iLoveWrappingStuff = iLoveWrappingStuff;
        }
    
        protected override bool IsValid(MyModel instance, object value)
        {
            var attempted = (string)value;
            return _iLoveWrappingStuff.SaysCanHazCheez(instance, attempted);
        }
    }
    

    With some helper classes (look over there), you wire it up e.g. in ASP.NET MVC like so in the Global.asax :-

    DataAnnotationsModelValidatorProvider.RegisterAdapterFactory(
        typeof(ValidatorServiceAttribute),
        (metadata, context, attribute) =>
            new DataAnnotationsModelValidatorEx(metadata, context, attribute, true));
    
    0 讨论(0)
提交回复
热议问题