3
votes

In the Azure app service mobile backend service, REST API requests are handled by TableController implementation. These methods can be invoked by using corresponding methods available in client SDKs. So, i can query for a particular entity and update its status from the client side.

But how to invoke them in the server side or within the same controller? For example, if I want to query for a particular todoItem and update its status from some custom method here like

  1. Use LookUp(id) to get the item
  2. Update the status
  3. Use UpdateAsync(id, item)

Here I don't know how to create a Delta object of TodoItem to call UpdateAsync(id, patch) method.

 public class TodoItemController : TableController<TodoItem>
{
    protected override void Initialize(HttpControllerContext controllerContext)
    {
        base.Initialize(controllerContext);
        initrackerserviceContext context = new initrackerserviceContext();
        DomainManager = new EntityDomainManager<TodoItem>(context, Request);
    }

    // GET tables/TodoItem
    public IQueryable<TodoItem> GetAllTodoItems()
    {
        return Query();
    }

    // GET tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
    public SingleResult<TodoItem> GetTodoItem(string id)
    {
        return Lookup(id);
    }

    // PATCH tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
    public Task<TodoItem> PatchTodoItem(string id, Delta<TodoItem> patch)
    {
        return UpdateAsync(id, patch);
    }

    // POST tables/TodoItem
    public async Task<IHttpActionResult> PostTodoItem(TodoItem item)
    {
        TodoItem current = await InsertAsync(item);
        return CreatedAtRoute("Tables", new { id = current.Id }, current);
    }

    // DELETE tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
    public Task DeleteTodoItem(string id)
    {
        return DeleteAsync(id);
    }
}
2

2 Answers

3
votes

Just use the standard Entity Framework mechanisms. For instance, to find and update a record with a status, you can just use the context:

var item = await context.TodoItems.Where(i => i.Id.Equals(myId)).FirstOrDefaultAsync<TodoItem>();
if (item != null) {
    item.Complete = true;
    context.Entry(item).State = EntityState.Modified;
    await context.SaveChangesAsync();
}

My EF coding is not the greatest ad-hoc, but you should get the idea. Just do the Entity Framework thing.

1
votes

It's better to use TableController.ReplaceAsync() method that is already implemented for us here in the source code of EntityDomainManager.

var item = Lookup(item.Id).Queryable.FirstOrDefault();
if (item != null) 
{
    item.Complete = true;
    item = await ReplaceAsync(item.Id, item);
}

The ReplaceAsync() method correctly handles the exceptions, so I would not recommend working directly with the EF context.