jeudi 1 octobre 2015

Implementing PUT in WEB API

I have an MVC 4 web api application with SQL and I need some help creating the controller code for the PUT method to update existing record in database. The problem is I cannot use the current user to attach the call, but instead I check the record based on existing string then I have to return the record ID number in order to update it.

This is my model

public class Laptop { public int Id { get; set; }
public virtual IList Programs { get; set; }
public Component Component { get; set; }
public string HostName { get; set; } public string Ident { get; set; }

}

controller :

[HttpPut] public HttpResponseMessage PutLaptop ( Laptop laptop)

    {
        string idnt = laptop.Ident;

            var mystr = db.Laptops    //Here I look for string Idnt in 
                .Where(c => c.Ident == idnt)  //database and select the 
                .Select(d =>d.Id)             //record ID
                .FirstOrDefault();
            int id = mystr;




            if (ModelState.IsValid && id == laptop.Id) //Here id is correct
            {                                          //record ID in 
                                                        // database but 
                                                      //device.Id is 0, why?
          db.Entry(laptop).State = EntityState.Modified;


                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    return Request.CreateResponse(HttpStatusCode.NotFound);
                }

                return Request.CreateResponse(HttpStatusCode.OK);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

    }

Is there a better way to implement this? Also, I cannot send the ID in the PUT call but instead I have to match the Idnt string in database in order to find the record ID then update it. Is this possible to implement ?




Aucun commentaire:

Enregistrer un commentaire