0

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?

  • Could you show us code for mapping to database? It seems, that your entities set id on savechanges and don't use id that you set before it. – Kirill Bestemyanov Jul 08 '14 at 20:26
  • Ehh... `SaveChanges` does throw validation errors, unless you disabled that. But I have a feeling that you a lot more going on than you show. For instance, how does an entity have this ChangeTracker, or a property IsValid? And why this double cast? And what is this ObjectState? Looks like you're using a framework that fights EF's default behavior. – Gert Arnold Jul 08 '14 at 20:42
  • The framework I am using is http://ntieref.codeplex.com/ and yes it does have behavior that differs from default EF. The answer below confirms that this behavior is a current shortcoming, so I await the resolution. – LorenNicole Jul 09 '14 at 12:44
  • Not an unimportant detail... next time mention this right away. – Gert Arnold Jul 09 '14 at 17:33

1 Answers1

0

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.

ChristofSenn
  • 337
  • 2
  • 6