David Catriel
David Catriel

Reputation: 375

Entity framework equivalent of ADO.Net's DataRow.HasErrors?

Would be nice if the Entity framework had the ADO.Net equivalent of DataRow.HasErrors.

I'm running into cases where the server returns errors on my save (such as "binary/string data would be truncated, non nullable fields set to null, etc), and there's no way to tell which entity caused the problem. In ADO.Net this was easier, since after telling the DataAdapter to save the changes I could just go through all datarows and just check the ones that had HasErrors on. Granted this would not pinpoint the field, but would at least tell me which row caused the problem.

I can't seem to find an Entity equivalent to this. Does anyone know if there is one?

Upvotes: 0

Views: 491

Answers (1)

kmp
kmp

Reputation: 10865

In both of the cases you describe you would get a DbUpdateException thrown when you attempt to save.

This exception has a property on it called Entries. You can use this property to get hold of the entities that caused the failure. Each entity is a DbEntityEntry object and that has a property that has the real entity plus loads more information about what the error was etc.

So in the case that you describe just catch the exception and look at the Entries collection to find out the root cause of the problem something like this:

try
{
    c.SaveChanges();
}
catch (DbUpdateException ex)
{                   
    IEnumerable<object> myBadEntities = 
        ex.Entries.Select(e => e.Entity);
}

Upvotes: 1

Related Questions