Search code examples
asp.netentity-frameworkexceptionmodelupdateexception

An exception of type 'Microsoft.EntityFrameworkCore.DbUpdateException' occurred in Microsoft.EntityFrameworkCore.dll


I am having trouble at very long time. Lets imagine this example:

public class Coordinate {

     public int id {get;set;}
     public int x {get;set;}
     public int y {get;set;}
}
public class Planet {

     public int id {get;set;}
     public string name {get;set;}
     public Coordinate coordinate {get;set;}
}

I have created two models, and the model Planet has the model Coordinate as attribute. Now imagine somewhere in the code I create one coordinate and it is stored in database. Imagine this is the coordinate:

Coordinate c = new Coordinate();
c.x = 1;
c.y = 2;

Then I add it to my database and it is saved.

But when I create a planet and I do:

planet.coordinate = c;

And then I try to add it to database I have the following error:

An exception of type 'Microsoft.EntityFrameworkCore.DbUpdateException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code

Additional information: An error occurred while updating the entries. See the inner exception for details.

I know I can change the attribute public Coordinate coordinate to public int coordinate_id but I want to do this with the Coordinate model instead.

I am using ASP NET CORE 1.0

Cumps


Solution

  • Your problem is that at this point, c already has an Id.

    With planet.Add, the planet and all coordinates attached to it will be set to Added in your DbSet's and upon calling SaveChanges, insert statements will be created. (Here I assume an autoincrement on your column and your Id property)

    When SaveChanges is completed, EF will see that the planet is in the database, but the Id of the just added coordinate is different (it was altered by DBMS, so now the coordinate is twice in your database, with two different Id's), so it will expect something went wrong and throw this exception.

    When you don't have problems with duplicate entries, set the Id to null or 0. Otherwise, there are two solutions:

    -Set only the FK property, not the navigation property

    or

    -Call SaveChanges only once (for example, just add the planet, however with added coordinates relationship fixup should lead to the same result)