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 'url' property that should be unique for every place.
public class Place { [ScaffoldColumn(false)] public virtual int PlaceID { get; set; } [DisplayName("Date Added")] public virtual DateTime DateAdded { get; set; } [Required(ErrorMessage = "Place Name is required")] [StringLength(100)] public virtual string Name { get; set; } public virtual string URL { get; set; } };
Why isn't there just a [Unique] data annotation you can place on it?
I have seen 1 or 2 discussions on this, but no talk of best practice. Using Code First can you somehow tell the database to set a unique constraint on the field in the database?
What is easiest way - and what is best practice?
As crazy as it might sound the best practice nowadays is to not use built-in validation and instead use FluentValidation. Then the code will be very easy to read and super-maintainable since validation will be managed on separate class meaning less spaghetti code.
Pseudo-example of what you are trying to achieve.
[Validator(typeof(PlaceValidator))] class Place { public int Id { get; set; } public DateTime DateAdded { get; set; } public string Name { get; set; } public string Url { get; set; } } public class PlaceValidator : AbstractValidator<Place> { public PlaceValidator() { RuleFor(x => x.Name).NotEmpty().WithMessage("Place Name is required").Length(0, 100); RuleFor(x => x.Url).Must(BeUniqueUrl).WithMessage("Url already exists"); } private bool BeUniqueUrl(string url) { return new DataContext().Places.FirstOrDefault(x => x.Url == url) == null } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With