Database Reference
In-Depth Information
{
throw new InvalidOperationException(
"Arrival date cannot be before departure date");
}
if (LeavesFrom == ArrivesAt)
{
throw new InvalidOperationException(
"Can't leave from and arrive at the same location");
}
}
}
}
5.
Override the SaveChanges() method in the DbContext with the code in Listing 8-13. This
will allow you to validate the changes before they are saved to the database.
Listing 8-13. Overriding the SaveChanges() Method
public partial class EFRecipesEntities
{
public override int SaveChanges()
{
this.ChangeTracker.DetectChanges();
var entries = from e in this.ChangeTracker.Entries().Where(e => e.State ==
(System.Data.Entity.EntityState.Added | EntityState.Modified | EntityState.Deleted))
where (e.Entity != null) &&
(e.Entity is IValidate)
select e;
foreach (var entry in entries)
{
switch (entry.State)
{
case EntityState.Added:
((IValidate)entry.Entity).Validate(ChangeAction.Insert);
break;
case EntityState.Modified:
((IValidate)entry.Entity).Validate(ChangeAction.Update);
break;
case EntityState.Deleted:
((IValidate)entry.Entity).Validate(ChangeAction.Delete);
break;
}
}
return base.SaveChanges();
}
}
 
Search WWH ::




Custom Search