VEF319: Validation in the Data Layer with Entity Framework

leathermumpsimusSoftware and s/w Development

Dec 13, 2013 (3 years and 8 months ago)

102 views

VEF319:
Validation in the Data Layer with
Entity Framework
Julie Lerman
The Data Farm
consultant/mentor
Microsoft MVP, INETA Speaker,
ASPInsider, MCP, VTdotNET Leader
contact
jlerman@theDataFarm.com
www.thedatafarm.com
blog
theDataFarm.com/blog
twitter
@julielerman
book web site
LearnEntityFramework.com
Julie Lerman
Objectives
• Validation API Overview
• Simple Property Validation
• Type Level Validation
• Validation Exceptions
• SaveChanges Validation
• Customizing Behavior
• Disconnected Scenarios
Validation Logic in Your Application
User Interface
Business Logic
Data Layer
Database
Entity Framework
“Core”
(in .NET 4.5)
(Object Services API (ObjectContext) & EntityClient API,
EntityObject, Enums & POCO support)
Code First
Designer Free
Model Support
DbContext API
Simpler Access
DbContext, DbSet, Validation, etc.


EF Designer
EntityFramework.DLL
Defining Validation Rules
•.NET ValidationAttributes
[Required], [StringLength], etc
Data
Annotations
• EF Specific
• Required, MaxLength
EF Fluent
API
• Type validation
IValidatableObject
• EF Specific
• Virtual DbContext method
ValidateEntry
Defining Rules: Validation Attributes
• System.ComponentModel.DataAnnotations

RegularExpression

StringLength

DataType

Required

Range

Custom

public class TwitterAlias
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[StringLength(30,MinimumLength=5)]
public string UserName { get; set; }
[RegularExpression
(@"(\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3})")]
public string Email { get; set; }
public string Bio { get; set; }
public byte[] Avatar { get; set; }
public ICollection<Tweet> Tweets { get; set;}
}
Not To Be Confused With . . .
TimeStamp
Column
Table
ComplexType
Examples of other non-Validating Data Annotations*
*All but TimeStamp are in System.ComponentModel.DataAnnotations.Schema
ForeignKey
InverseProperty
DatabaseGenerated
NotMapped

Defining Rules: IValidateableObject
using System.ComponentModel.DataAnnotation;

public class Menu: IValidatableObject
{
…properties…

public IEnumerable<ValidationResult>
Validate(ValidationContext validationContext)
{
if (Dessert!= “Chocolate”){
yield return new ValidationResult
(“Try again", new[] { “Flavor” });}

if (StartTime > EndTime){
yield return new ValidationResult
(“Start Time too late", new[]{“StartTime”, “EndTime”});}
}
}
Validation Results
DbEntityValidation
Exception
EntityValidationErrors
(Object Instance A)
DbValidationError
(Failure 1)
DbValidationError
(Failure 2)
EntityValidationError
(Object Instance B)
DbValidationError
(Failure 1)
EntityValidationError
(Object Instance C)
DbValidationError
(Failure 1)
ValidateEntity Does the Checking
• DbContext.ValidateEntity
• Default Behavior

Executes before SaveChanges

Checks Added & Modified Entities
• Customize

Override ValidateEntity

DbContext.ShouldValidateEntity

ValidateOnSaveEnabled configuration

Overriding ValidateEntity
protected override DbEntityValidationResult ValidateEntity
(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
if (entityEntry.Entity is Reservation)
{
if (StartDate > EndDate);
{
errors.Add(new DbValidationError
(“StartDate",“StartDate is later than EndDate" ));
return new DbEntityValidationResult(entityEntry, errors);
}
}
return base.ValidateEntity(entityEntry, items);
}
Processing Multiple Validations
3. Entity Type-level validation
Including base entity types
Attributes & IValidatableObjects
2. Complex Type level validation
Including base types
Attributes & IValidatableObjects
1. Property-level validation
Entity & base classes
Complex type & base classes
if
valid
if
valid
Validation Trigger Workflow
Source: “Programming Entity Framework: DbContext”
Triggering Validation
• Call explicitly

Entry(instance).GetValidationResult

DbContext.GetValidationErrors( )
• SaveChanges calls ValidateEntity

ValidateEntity calls GetValidationResult

Add more logic into ValidateEntity
• ConfigurationValidateOnSaveEnabled

true by default
Validating in Virtual SaveChanges
• Use for non-validation logic
• When entity by entity validation is too
expensive
• *SavingChanges is for backward compatability only
Disconnected Apps
• Handle validation errors in server logic

Return appropriate details to client


Entity Framework Validation
• Built in validation
• Reduce your own validation code
• API uses existing .NET validation tools
• Validation at SaveChanges by default
• Explicitly force validation for more control

Override SaveChanges to avoid wasted
entity by entity validation

Resources
• Julie Lerman:
thedatafarm.com/blog
• LearnEntityFramework.com
• Pluralsight.com videos
• MSDN Developer Center:
msdn.com/data/ef
• EF Team:
blogs.msdn.com/adonet
• http://blogs.msdn.com/b/adonet/archive/2011/05/27/ef-4-1-validation.aspx
consultant/mentor
Microsoft MVP, INETA Speaker,
ASPInsider, MCP, VTdotNET Leader
contact
jlerman@theDataFarm.com
www.thedatafarm.com
blog
theDataFarm.com/blog
twitter
@julielerman
book web site
LearnEntityFramework.com
Julie Lerman