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?

有帮助吗?

解决方案 2

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top