0

I want to expose a list of services from my DB or just return one service detail via Web API with my EF DBmodel . I used VS2012 Web API scaffolding, quite easy so far and it works and return the list of services in JSON when I hit the URL(.../api/Services). The problem is that when I want to obtain just one service URL(.../api/Services/1), I still obtain the full list of all services although when I trace it seems to return only a count of 1 object.

What happening here?

Here are the 2 controller actions.

ps: I also tried using a .Where() instead of .Find() but the result is the same in both cases.

    // GET api/Services
    public IEnumerable<service> Getservices()
    {
        var services = db.services.Include(s => s.Category).Include(s => s.Country).Include(s => s.StateProvince).Include(s => s.Territory);
        return services.AsEnumerable();

    }
    // GET api/Services/5
    public service Getservice(int id)
    {
        service service = db.services.Find(id);          
        if (service == null)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
        }
        return service;
    }
SPandya
  • 1,161
  • 4
  • 26
  • 63

2 Answers2

0

Try handling it as: var service = db.services.Single(s => s.Id == id)

Chris
  • 772
  • 3
  • 8
0

First, check if your database has a single item for your query or not.

If you are querying by primary key then db.services.SingleOrDefault(s => s.Id == id) should do.

You will need to handle the exception if you are querying on some field which may give back more than one result.

The variant of filtering (Single, SingleOrDefault, First, FirstOrDefault) that you use will depend upon the exact semantics of the code.

ashutosh raina
  • 9,228
  • 12
  • 44
  • 80
  • Thnaks raina & Chris. I tried what you proposed but I still obtain the full list even if I select only one record. – Jean Poulin Oct 24 '13 at 02:10
  • Thnaks raina & Chris. I tried what you proposed but I still obtain the full list even if I select only one record. What is weird is that when I trace step by step and look at the content of service (return service;) at the moment I return it contains only one record. but it renders all Json records in my web page. I never experienced this when I did a standard MVC action returning a JsonResult. It must be related to the fact that service has category + country + state external keys because if I do the same scaffolding web API controller on the table categories it works. – Jean Poulin Oct 24 '13 at 02:16
  • OK Fixed.. A bit related to my last remarks it was because a side effect to reach the whole object graph because it is by default LazyLoading. I turned it off in my xxModel.Context.cs file with this.Configuration.LazyLoadingEnabled = false; and it now just return the record I want. – Jean Poulin Oct 24 '13 at 02:57