user1012506
user1012506

Reputation: 2118

How get the wrong entity in saveChanges()

When I can saveChanges() for some entities, and one entity was wrong, I go to exception catch and I want to insert to Log the stateEntity that was wrong, If I will get the specific entity I can do it. The method of save use for add,update and remove

Can I catch the wrong entity?

My save method:

  public long save(IResponse res, Context context)
            {
                try
                {

                    foreach (Entity ent in response.Entities)
                    {
                        context.Entry(ent).State = ent.getEntityState();
                    }

                    return context.SaveChanges();
                }

                catch (Exception ex)
                {
                    string errorMessages = ex.InnerException.InnerException.ToString();            
                    res.ExceptionDBDesc = errorMessages;
                    res.WrongEntState= ???    //add/modify/remove

                }

Upvotes: 0

Views: 75

Answers (1)

Pankaj Kumar
Pankaj Kumar

Reputation: 105

Try it :

try
{
    _context.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
    Exception raise = dbEx;
    foreach (var validationErrors in dbEx.EntityValidationErrors)
    {
        foreach (var validationError in validationErrors.ValidationErrors)
        {
            string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage);
            //raise a new exception inserting the current one as the InnerException
            raise = new InvalidOperationException(message , raise);
        }
    }
    throw raise;
}

Upvotes: 2

Related Questions