Reputation: 1822
Which is the best approach for updating multiple records at a time using ASP.NET Web API and OData against an Entity Framework database?
Let's suppose we have a table in our database with a "State" field, and we want to do something similar to this SQL statement: "UPDATE Table set State = 1". Should I do a loop with GET and PUT for each record? I do not like it at all, I guess it must be a better way to accomplish this.
Thank you
Upvotes: 1
Views: 2098
Reputation: 415
OData supports such kinds of operations. You can use OData Action to update the state.
Blog: odata-actions-and-functions
Sample: ODataActionSample
Upvotes: 0
Reputation: 4793
It looks like you can't do this natively in OData, but there is one approach that will definitely work; just use a native Web API action to perform the update.
E.g.
[HttpPut]
[Route("resources/state")]
public IHttpActionResult UpdateState(int newState)
{
db.Database.SqlCommand("UPDATE Table SET State = @p0", newState);
}
You'd call this from a client using a PUT /resources/state?newState=1
.
It might be clearer to make newState
an enum:
public enum State
{
New = 0,
Processed = 1,
Error = 2,
etc.
}
[HttpPut]
[Route("resources/state")]
public IHttpActionResult UpdateState(State newState)
{
db.Database.SqlCommand("UPDATE Table SET State = @p0", (int)newState);
}
Then your call becomes PUT /resources/state?newState=Processed
which is a little clearer.
Upvotes: 1