rkralston
rkralston

Reputation: 386

DbContext.SaveChanges Fails to Save Valid Entities

I'm using EF 5 with Code First POCO.

Here is the repository's SaveChanges implementation:

    public virtual List<DbEntityValidationResult> SaveChanges()
    {
        var errors = new List<DbEntityValidationResult>();
        try
        {
            DbContext.SaveChanges();
        }
        catch (DbEntityValidationException ex)
        {
            errors.AddRange(ex.EntityValidationErrors);
        }

        return errors;
    }

A single validation error causes no entities to be written to the database. I had expected valid entities to be written out and to receive errors for invalid entities.

Is this how EF is supposed to act?

Upvotes: 0

Views: 2325

Answers (2)

rkralston
rkralston

Reputation: 386

I did some more digging. EEF does not attempt to write the Entities. It calls validation from the Object Context first. If any entities fail, they are added to DbValidationResult and the save is canceled.

For bulk transactions, you can remove those entities and handled any errors and then resave.

Once all the Entities validate, EF writes changes to the database as appropriate.

Upvotes: 0

Nick Butler
Nick Butler

Reputation: 24383

That's the way EF works.

SaveChanges() creates a transaction and attempts to save all the changes in the context.

If any writes fail for any reason, the whole transaction is rolled back and no changes are persisted.

Upvotes: 2

Related Questions