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 codeAdditional 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
1
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)
4
Having a look at the inner exception will give you a more detailed look at what is going wrong.
To do this, in debug mode, when the exception shows. Click view detail and follow the tree until you find inner exception.
There may be duplicate rows, primary key issues or structure issues.
3
I was having the same problem and I realized that I was creating more than only one instance to access the database.
So the solution I took was creating a class that made only one access.
class SingletonContext {
private static Context _context;
public static Context GetInstance() {
if (_context == null) {
_context = new Context();
}
return _context;
}
}
And in every access to the database layer I call the GetInstance(), like this:
private static Context _context = SingletonContext.GetInstance();
I also got the similar error, while creating the post method but I resolved this by doing the following
Make sure that you have included the following code in
-
Constructor
In this import the interface file of which the foreign is key belongs to -
HttpPost method
[HttpPost] [ProducesResponseType(204)] [ProducesResponseType(400)] [ProducesResponseType(404)] //IMPORTANT TO INCLUDE [FromQuery] public IActionResult CreateBatch([FromQuery] int trackId, [FromBody] BatchDto batchCreate) { if(batchCreate == null) return BadRequest(ModelState); var batch = _batchInterface.GetBAtches() .Where(c => c.batchName.Trim().ToLower() == batchCreate.batchName .TrimEnd().ToLower()); if (batch == null) return BadRequest(ModelState); var batchMap = _mapper.Map<Batch>(batchCreate); batchMap.track = _trackInterface.GetTrack(trackId); //Important if (!ModelState.IsValid) return BadRequest(ModelState); if(!_batchInterface.CreateBatch(batchMap)) { ModelState.AddModelError("", "Something went in the creation of batch"); return StatusCode(500, ModelState); } return Ok("Successfully created Batch"); }
2