5

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

1
  • "See the inner exception for details." so what does it say? Commented Aug 3, 2016 at 19:11

4 Answers 4

3

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)

Sign up to request clarification or add additional context in comments.

4 Comments

I just realized: There is a third solution by setting the EntityState of c to EntityState.Modified.
I like the third solution, so when adding the planet I do "context.Entry(planet.coordinate).State = EntityState.Modified ?
yes. However, now I think about that, this would only avoid a DbUpdateConcurrencyException and duplicate entries. I do think there is another error in your code to throw a DbUpdateException, you should look at the InnerException.
It doesnt duplicate anything, your third solutions is right, thanks mate!
3

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 Comments

This doesn't answer the question, it only gives debugging advice.
I understand David, but with low rep. I cannot comment... so what should I do.
Go and earn 50 rep, it doesn't take long. You can do it by suggesting edits to questions, there's a lot of them that need formatting help.
0

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

Comments

-2

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

  1. Constructor In this import the interface file of which the foreign is key belongs to

  2. 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 Comments

This is not an answer to this question. It may have solved a similar issue in your code, but it is meaningless without knowing all underlying details.
sorry, Now I changed that. But I also got the same error so

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.