1
\$\begingroup\$

Here is my method that I use to get one entity in an ASP.NET Web API application.

[EnableQuery]
public virtual HttpResponseMessage GetById([FromODataUri]int id)
{
    // get concrete entity from repository
    var entity = repository.GetById(id);
   // check entity
    if (entity == null)
    {
        var message = string.Format("No {0} with ID = {1}", GenericTypeName, id);
        return ErrorMsg(HttpStatusCode.NotFound, message);
    }

    // problem
    return Request.CreateResponse(HttpStatusCode.OK, SingleResult.Create(repository.Table.Where(t => t.ID == id)));
}

I'm using SingleResult for OData request (because $expand for single entity does not work if I do not create SingleResult). But in this case I repeatedly do almost the same action repository.GetById(id); and repository.Table.Where(t => t.ID == id).

How can I improve it?

\$\endgroup\$
5
\$\begingroup\$

You can wrap the single entity into an IQueryable. Something like this should work:

SingleResult.Create(new[]{entity}.AsQueryable());

You could write a helper function that uses this trick to convert from a single T to an IQueryable<T>. There may even be a built-in way of doing this.

\$\endgroup\$
  • \$\begingroup\$ I wish [EnableQuery] + SingleResult knew how to return 404 OOTB \$\endgroup\$ – bkwdesign Apr 27 '17 at 19:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.