I'm very new to EF4. I've posted a couple of times I think regarding inheritance, validation but my overall aim is to reduce the amount of code I write as much as possible. I'm not interested (yet) in POCOs, masses of ObjectContext fiddling: I want the benefit of EF and minimum of coding.
So, the thorny issue of validation. Take a look at this simplified example and (aside from DRY Buddies and dodgy usings aliases), is this looking like a half-decent approach?
namespace Model
{
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
using DataAnnotations = System.ComponentModel.DataAnnotations;
using Validation = Microsoft.Practices.EnterpriseLibrary.Validation;
[HasSelfValidation]
[DataAnnotations.MetadataType(typeof(PersonValidator))]
public partial class Person
{
[SelfValidation]
public Validation.ValidationResults Validate()
{
var validationResults = Validation.Validation.Validate(this);
if (string.IsNullOrEmpty(this.LastName) || this.LastName.Length > 4)
{
validationResults.AddResult(new Validation.ValidationResult("This is a test error message for a custom validation error.", this, null, null, null));
}
return validationResults;
}
}
[HasSelfValidation]
public class PersonValidator
{
[NotNullValidator(MessageTemplate = "First Name must be supplied.")]
[ContainsCharactersValidator("Rcd", ContainsCharacters.All, MessageTemplate = "{1} must contains characters \"{3}\" ({4}).")]
[StringLengthValidator(5, 50, MessageTemplate = "{1} (\"{0}\") must be between {3} ({4}) and {5} ({6}) characters in length.")]
public string FirstName { get; set; }
[NotNullValidator(MessageTemplate = "Last Name must be supplied.")]
[ContainsCharactersValidator("Wes", ContainsCharacters.All, MessageTemplate = "{1} must contains characters \"{3}\" ({4}).")]
[StringLengthValidator(5, 50, MessageTemplate = "{1} (\"{0}\") must be between {3} ({4}) and {5} ({6}) characters in length.")]
public string LastName { get; set; }
}
}
There's something rather cool about this. I can call the above like this:
var validationResults = person.Validate();
BUT, if I just want some basic checking, I can strip out Validate(), the [SelfValidation] stuff, keep the attributes and then just call:
var validationResults = Validation.Validate(person);
I only need to include as much validation as I need and there's ZERO configuration in web.config.
How's the cut of my jib? :)
Richard