Entity framework db model的驗證機制 20130914

529 views

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
529
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
3
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Entity framework db model的驗證機制 20130914

  1. 1. Entity Framework DB Model的驗證機制 Bryan Lin 2013/09/14
  2. 2. 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
  3. 3. Client-Side and Server-Side Validation with Data Annotations • 在DB Model中加上Data Annotations的Attribute,就可以同時做到 client端跟Server端的驗證
  4. 4. 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; } }
  5. 5. Client-Side and Server-Side Validation with Data Annotations [Required] public string Title { get; set; }
  6. 6. Client-Side and Server-Side Validation with Data Annotations
  7. 7. 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); } }
  8. 8. Code First Fluent API Validations • 在Action階段,若資料長度超過時會拋出DbEntityValidationException
  9. 9. 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(); } }
  10. 10. 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” }); } } }
  11. 11. Using IValidatableObject with POCOs for More Complex Validations
  12. 12. Implementing Validation in the Context with ValidateEntity • 可以Override DbContext的ValidateEntity方法來實作所需要的驗證邏 輯
  13. 13. 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); } }
  14. 14. Explicitly Triggering Validation • 當我們對DbContext做SaveChange時,會觸發驗證 • 也可以使用DbContext.GetValidationErrors來觸發驗證
  15. 15. 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); } }
  16. 16. FAQ

×