private void TestDetectChangesWithSaveChangesAndValidation(bool validateOnSaveEnabled) { using (var context = new ValidationTestContext()) { context.Database.Initialize(force: false); using (new TransactionScope()) { context.Configuration.ValidateOnSaveEnabled = validateOnSaveEnabled; var food = context.Entry(new Category("FOOD")); context.Categories.Add(food.Entity); context.SaveChanges(); Assert.Equal(null, food.Entity.DetailedDescription); Assert.Equal(EntityState.Unchanged, food.State); food.Entity.DetailedDescription = "foo"; Assert.Equal(EntityState.Unchanged, food.State); context.ValidateEntityFunc = (entry) => { Assert.Equal( validateOnSaveEnabled ? EntityState.Modified : EntityState.Unchanged, entry.State); entry.State = EntityState.Unchanged; food.Entity.DetailedDescription = "bar"; Assert.Equal(EntityState.Unchanged, entry.State); return new DbEntityValidationResult(entry, Enumerable.Empty <DbValidationError>()); }; context.SaveChanges(); Assert.Equal(validateOnSaveEnabled ? "bar" : "foo", food.Entity.DetailedDescription); food.Reload(); Assert.Equal(validateOnSaveEnabled ? null : "foo", food.Entity.DetailedDescription); } } }
public void SaveChanges_throws_on_validation_errors_implementation(Func<DbContext, int> saveChanges) { using (var context = new ValidationTestContext()) { context.Database.Initialize(force: false); using (new TransactionScope()) { context.ValidateEntityFunc = (entry) => { return new DbEntityValidationResult(entry, new[] { new DbValidationError("Id", "error") }); }; context.Categories.Add(new Category("FOOD")); Assert.Throws<DbEntityValidationException>(() => context.SaveChanges()).ValidateMessage( "DbEntityValidationException_ValidationFailed"); } } }
private void TestValidateEntityWithSaveChanges(bool validateOnSaveEnabled) { using (var context = new ValidationTestContext()) { context.Database.Initialize(force: false); using (new TransactionScope()) { context.Configuration.ValidateOnSaveEnabled = validateOnSaveEnabled; bool validateCalled = false; context.ValidateEntityFunc = (entry) => { validateCalled = true; return new DbEntityValidationResult(entry, Enumerable.Empty <DbValidationError>()); }; context.Categories.Add(new Category("FOOD")); context.SaveChanges(); Assert.True(validateOnSaveEnabled == validateCalled); } } }