Cristhian Boujon
Cristhian Boujon

Reputation: 4190

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?

Upvotes: 4

Views: 28185

Answers (4)

sachin
sachin

Reputation: 91

Yes ... Always make sure that if our entities has guids then 'StoreGeneratedPattern' has to set with value "Identity". because by default sqlserver doesnot add values for guid columns.

It can be set from edmx by selecting entity-right click-properties-select guid column-set storedGeneratedPattern to identity.

Or by assigning 'Guid.newGuid()' value to column from code itself. ex. product.Id = Guid.newGuid();

Upvotes: 0

Cristhian Boujon
Cristhian Boujon

Reputation: 4190

Based on Despertar's answer I could solved my problem. Entity Framework has an option called StoreGeneratedPattern. This option indicates the behavior when need to set an primary key id. By default this option is "None", so if you want the autoincrement, set the option StoreGeneratedPattern as "Identity" . This is the link that I've read.

Upvotes: 0

Despertar
Despertar

Reputation: 22352

It doesn't mean that you are doing an Update, that just means a SQL error occurred. You need to read the inner exception to find out what the actual error is. From the looks of it, it may be something related to a primary key, or foreign key constraint, ie. you are adding an item and that primary key is already in the table. But again, the actual error will give you more details.

If you are running in Visual Studio it should automatically break on the exception and you can expand the inner exception property. If not you can put a try/catch block and log it to a file or write to a console. Exception.ToString() will show all inner exceptions as well, as SQL errors tend to wrap the true error inside a few different exceptions.

private void InsertarIntoDataBase()
{
    try 
    {
        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();
    }
    catch (Exception e)
    {
        Console.WriteLine(e); // or log to file, etc.
        throw; // re-throw the exception if you want it to continue up the stack
    }
}

Upvotes: 4

David Anderson
David Anderson

Reputation: 13670

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().

Upvotes: 11

Related Questions