Entity framework db model的驗證機制 20130914
Upcoming SlideShare
Loading in...5
×
 

Entity framework db model的驗證機制 20130914

on

  • 394 views

 

Statistics

Views

Total Views
394
Views on SlideShare
394
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Entity framework db model的驗證機制 20130914 Entity framework db model的驗證機制 20130914 Presentation Transcript

  • Entity Framework DB Model的驗證機制 Bryan Lin 2013/09/14
  • Agenda • Client-Side and Server-Side Validation with Data Annotations • Code First Fluent API Validations • Using IValidatableObject with POCOs for More Complex Validations • Implementing Validation in the Context with ValidateEntity • Explicitly Triggering Validation
  • Client-Side and Server-Side Validation with Data Annotations • 在DB Model中加上Data Annotations的Attribute,就可以同時做到 client端跟Server端的驗證
  • Client-Side and Server-Side Validation with Data Annotations public class Blog { public int Id { get; set; } public string Title { get; set; } public string BloggerName { get; set; } public DateTime DateCreated { get; set; } public virtual ICollection<Post> Posts { get; set; } } } public class Post { public int Id { get; set; } public string Title { get; set; } public DateTime DateCreated { get; set; } public string Content { get; set; } public int BlogId { get; set; } public ICollection<Comment> Comments { get; set; } }
  • Client-Side and Server-Side Validation with Data Annotations [Required] public string Title { get; set; }
  • Client-Side and Server-Side Validation with Data Annotations
  • Code First Fluent API Validations • 在DbContext產生的時候做資料的驗證 public class BlogContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } public DbSet<Comment> Comments { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Blog>().Property(p => p.BloggerName).HasMaxLength(10); } }
  • Code First Fluent API Validations • 在Action階段,若資料長度超過時會拋出DbEntityValidationException
  • Code First Fluent API Validations public ActionResult Edit(int id, Blog blog) { try { db.Entry(blog).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } catch(DbEntityValidationException ex) { var error = ex.EntityValidationErrors.First().ValidationErrors.First(); this.ModelState.AddModelError(error.PropertyName, error.ErrorMessage); return View(); } }
  • Using IValidatableObject with POCOs for More Complex Validations public class Blog : IValidatableObject { public int Id { get; set; } [Required] public string Title { get; set; } public string BloggerName { get; set; } public DateTime DateCreated { get; set; } public virtual ICollection<Post> Posts { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (Title == BloggerName) { yield return new ValidationResult ("Blog Title cannot match Blogger Name", new[] { "Title", “BloggerName” }); } } }
  • Using IValidatableObject with POCOs for More Complex Validations
  • Implementing Validation in the Context with ValidateEntity • 可以Override DbContext的ValidateEntity方法來實作所需要的驗證邏 輯
  • Implementing Validation in the Context with ValidateEntity protected override DbEntityValidationResult ValidateEntity (System.Data.Entity.Infrastructure.DbEntityEntry entityEntry, IDictionary<object, object> items) { var result = new DbEntityValidationResult (entityEntry, new List<DbValidationError>()); if (entityEntry.Entity is Post && entityEntry.State == EntityState.Added) { //驗證邏輯 result.ValidationErrors.Add( new System.Data.Entity.Validation.DbValidationError("Title", "Post title must be unique.") ); } if (result.ValidationErrors.Count > 0) { return result; } else { return base.ValidateEntity(entityEntry, items); } }
  • Explicitly Triggering Validation • 當我們對DbContext做SaveChange時,會觸發驗證 • 也可以使用DbContext.GetValidationErrors來觸發驗證
  • Explicitly Triggering Validation foreach (var validationResults in db.GetValidationErrors()) { foreach (var error in validationResults.ValidationErrors) { Debug.WriteLine("Entity Property: {0}, Error {1}", error.PropertyName,error.ErrorMessage); } }
  • FAQ