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

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?


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


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.

| improve this answer | |
  • \$\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.