Search code examples
databaseasp.net-mvc-4updatemodel

How to update database where column = string


I am sending a string to my controller containing seat numbers: A1, A2 etc. And a string containing an ID.

I want to select each db row from the seats table where the column: seatnum equals each of the seat numbers in the seatss string and update a related column called status from 0 to the ID string.

I have used the below code to select the row where the seatnum = seatss string and return the matching row as a json object. This works if there is one seat number in the string but not if there are multiple. I'm assuming I would need to implement an array of some sort but have no idea how to do so. The seat numbers are posted as this: A1, A2, A3. So I'd like to separated/explode them on the , and then match them to the database rows.

    //
    // POST: /seats/



    public JsonResult Checkout(string seatss, string ID)
    {
        var seats = from b in db.seats
                    select b;


        seats = seats.Where(b => b.seatnum.Equals(seatss)); // Selects the db row where .seatnum = string seatss.

        //Update seatnum to the value of seatss


        return Json(seats, JsonRequestBehavior.AllowGet); // returns the selected seats as a json object.


    }

So in summary I need a way to match each seat number in the string to the corresponding seatnum in the database and update the status to the integer contained in the ID string.

My database table(seats) has two columns called seatnum and status. The seatnum column contains rows: A1 etc and the status is 0 by default.


Solution

  • You could either change the way that you are passing your seat numbers, so instead of a string parameter named seats your action could expect an array or a generic list of string values, or you could just cast your current string parameter to an array and then modify you LINQ query to use a contains function. The sample provided is of the latter implementation since the former is a little more involved, of course this is untested:

    public JsonResult Checkout(string seatss, string ID)
    {
        var seats = from b in db.seats
                    select b;
    
    
        seats = seats.Where(b => seatss.Contains(b.seatnum));
    
        foreach(var seat in seats)
        {
             ... Perform status update on seat
        }
    
        return Json(seats, JsonRequestBehavior.AllowGet); // returns the selected seats as a json object.
    
    
    }