Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InnerException in Entity Framework when I try add an entity

I'm trying to insert a entity into my database with Entity Framework. See below:

private void InsertarIntoDataBase()
{

    Juego game = db.games.First(g => g.Id == anId);
    Day d = new Day {
                       DayNumber = this.Number,
                       Game = game // This is a relationship. One Day has one game 
                    };
    db.AddToDay(d);
    db.SaveChanges();
}

This is always for an insert, not an update. The first time that I run my app, it works, afterwards it stops working, throwing this exception An error occurred while updating the entries. See the InnerException for details.. (I'm really sure that I did not change anything).

Why does the framework think I'm updating? And what am I wrong?

like image 415
Cristhian Boujon Avatar asked Sep 16 '25 07:09

Cristhian Boujon


1 Answers

SaveChanges will throw a System.Data.Entity.Infrastructure.DbUpdateException if your update command fails, and it wraps a System.Data.UpdateException that finally wraps a System.Data.SqlClient.SqlException. It is also important to make a note that the inner-inner exception can be something other than a SqlException depending on the Entity Framework provider you are using.

If you unwrap these, you can get down to the raw SqlError objects that give you the specific details about problems with your update.

try 
{
    db.SaveChanges();
}
catch (DbUpdateException ex) 
{
    UpdateException updateException = (UpdateException)ex.InnerException;
    SqlException sqlException = (SqlException)updateException.InnerException;

    foreach (SqlError error in sqlException.Errors)
    {
        // TODO: Do something with your errors
    }
}

You can also gain a lot of power and control by also catching System.Data.Entity.Validation.DbEntityValidationException which will show you any validation errors that occurred during the call to SaveChanges. The default behavior is to validate changes on save. You can also pre-validate changes by calling DbContext.GetValidationErrors().

like image 106
David Anderson Avatar answered Sep 17 '25 22:09

David Anderson