Ewald Bos Ewald Bos - 1 month ago 6
JSON Question

Retrieving Records and Saving to a Database in a single C# Web Service

Hi i am trying to combine a C# webservice in azure with a get and a post at the same time, the idea is to get the details of a CD by the uniqueCDcode and the webservice outputs just the json information AND the uniqueCDcode needs to be stored in a different table CDClicked to i get a list of all the clickedCD's so i am able to take the last 50 as for trending etc. but don't really seem to get it to work. This is what i have so far

//// WS# 00002 GET THE ALBUM DETAILS
[Route("api/Music/Album/{uniqueCDcode}")]
public HttpResponseMessage GetAlbum(int uniqueCDcode)
{
return Request.CreateResponse(HttpStatusCode.OK,
new { AlbumMusic = db.Music
.Where(am => am.uniqueCDcode == uniqueCDcode);

db.CDClicked.Add(uniqueCDcode);

}

Answer

You need to retrieve your record/do the save, then return the response. The Add() method call to dbContext (second part) isn't working because the return statement is returning a value first, and then stopping the execution of your service, so it never gets to the second part. Your logic needs to be done before the return statement.

For example:

[Route("api/Music/Album/{uniqueCDcode}")]
public HttpResponseMessage GetAlbum(int uniqueCDcode)
{
    db.CDClicked.Add(uniqueCDcode);

    return Request.CreateResponse(HttpStatusCode.OK, 
        new { AlbumMusic = db.Music
            .Where(am => am.uniqueCDcode == uniqueCDcode )});
}

You also had some formatting issues in the code. Your braces and parens didn't match up (at least in the code that you pasted into SO.) I corrected in my answer below.

Note: I can't test the code at the moment due to hurricane-related issues, but this is the general concept to get you going again.

Comments