ElenaDBA ElenaDBA - 26 days ago 8
C# Question

Partial update in Web API is not working

I created a post method in my Web API to do a partial update of one table - to change Order Status field in the table. here is what I got so far:

public IHttpActionResult UpdateOrderStatus(Order ord)
{
try
{
if (!ModelState.IsValid)
{
throw new ProcessException("One or more values are invalid, please check.");
}
using (MyContext ctx = new MyContext())
{
ord.StatusID = 3;
ctx.SaveChanges();

return CreatedAtRoute("DefaultApi", new { id = ord.OrderID }, ord);
}
}
catch (Exception ex)
{
throw new ProcessException(ex.Message);

}
}


I am stepping through the code and everything seems to be working - no errors, but the database is not getting updated. What am I doing wrong?

Update:

Set the StatusID in the object BEFORE passing it to the Web API method:


var ord = { "OrderID": 1, "OrderDate": CurrentDate, "StatusID": 3};


public IHttpActionResult UpdateOrderStatus(Order ord)
{
try
{
if (!ModelState.IsValid)
{
throw new ProcessException("One or more values are invalid, please check.");
}
using (MyContext ctx = new MyContext())
{
ctx.Entry(ord).State = EntityState.Modified;
ctx.SaveChanges();

return CreatedAtRoute("DefaultApi", new { id = ord.OrderID }, ord);
}
}
catch (Exception ex)
{
throw new ProcessException(ex.Message);

}
}

Rob Rob
Answer

If you're using EntityFramework then you need to inform the context about the Order object you are updating. In EF6 you would typically have a DbSet property on the context called Orders, so I'd advise adding ctx.Orders.Attach(Order) before you set the StatusID

Comments