Search code examples
c#entity-frameworkvalidationn-tier-architecturesavechanges

No Exception thrown on SaveChanges() for invalid entities using N-Tier Entity Framework


There are certain situations when entity.IsValid is false but no exception is thrown on SaveChanges(). The modelChangeSet only returns Valid entities (by default) and does not throw any exceptions for entities that are not valid. Thus the invalid entities remain in the datacontext with a modified or added state, and no exception is caught. For example, if I create a new entity (DataContext.EntitySet.CreateNew()) with a duplicate primary key, the entity is invalid, but calling SaveChanges() does not throw an exception. Can you recommend a way to obtain validation error messages when calling SaveChanges()?

As a workaround, I am checking for InValid entities before calling SaveChanges() (client-side validation), and only calling SaveChanges() if all the entities are valid.

foreach (Entity entity in context.EntitySet.Where(x =>   x.ChangeTracker.State.Equals(ObjectState.Added) || x.ChangeTracker.State.Equals(ObjectState.Modified)))
{
   if (!entity.IsValid)
   {
          MessageBox.Show(((System.ComponentModel.IDataErrorInfo)(NTier.Common.Domain.Model.Entity)entity).Error);
          invalidEntityFound = true;    
    }
}

If (!invalidEntityFound)
   Context.SaveChanges()

Would setting the GetChangeSet() method parameter includeOnlyValid=false change the process flow of SaveChanges()? Is there a way to set that parameter value?

@ChristofSenn Do you have any suggestions?


Solution

  • This is a current shortcoming of the N-Tier Entity Framework. Please report this as an issue on the project's site and I'm going to follow up on this.