I have a web API which has a scaffold-ed ApiController
. In update method (PUT
) following code segment updates the entity in the database.
_context.Entry(customers).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CustomersExists(id))
{
return NotFound("Not found");
}
else
{
throw;
}
}
But I found out that this only updates the attributes in Customer
model only, It does not propagate to referenced entities. As an example, There are Orders table which stores orders of each customer.
public partial class Customers
{
public Customers()
{
Orders= new HashSet<Orders>();
}
public string Description { get; set; }
public string Name { get; set; }
public virtual ICollection<Orders> Orders { get; set; }
}
So the request to update a customer can have updated order details as well. But,
_context.Entry(customers).State = EntityState.Modified;
this line fails to update Orders table if there is a change. After trying out many methods, I found out that,
_context.Customers.Update(customers);
manages to update everything successfully. But problem with that is if the current request has only 2 Orders and the update request has additional order(3 orders), again the update fails.
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded.
Edit: There are no any connections to the database. So concurrency exception is impossible.
My JSON request looks like this.
{
"orders":[
{
"id": "1",
"date": "2018/10/29"
},
{
},
],
"name":"test_name",
"description":"test_description",
}
Any help will be highly appreciated. Thank you.