1

i am creating a database application in mvc .net with sql server database.i have a table name seatplans with fields id,layout_id,seat_no,seat_id,booked i want to update the database with the following quesy inside the controller action

update seatplanes set booked=1 where seatid=seat_id and layoutid=layout_id

my controller action is as follows but i am unable to update the database

 [HttpPost]
    public ActionResult Seatbook(String seat_id, String seat_no, int layout_id)
    {
        //  int id = 10;
        SeatPlans S = new SeatPlans();
        S.seat_id = seat_id;
        S.seat_no = seat_no;
        S.layout_id = layout_id;
        S.booked = 1;
        if (ModelState.IsValid)
        {
            var OldInsObj = db.SEATPLAN.Find(seat_id,layout_id);
            S.Id = OldInsObj.Id;
            //var OldInsObj = db.SEATPLAN.Find(d=>d.seat_id==seat_id , d=>d.layout_id==layout_id).ToList();
             db.Entry(S).State = EntityState.Modified;
            db.SaveChanges();
            //  return RedirectToAction("Index");
        }


        return View("Index");
    }

can i update the database without using the stored procedure.

1
  • I suggest putting the initialization of the SeatPlans object within the if-clause. Commented Jun 1, 2016 at 10:30

1 Answer 1

1

Firstly I think you want to have a read of the documentation for Entity Framework, it'll get you going with all you need.

However, to answer your question in order to update a database entry you'd want to first get the entry:

var OldInsObj = db.SEATPLAN.Where(s => s.seat_id == seat_id 
    && s.layout_id == layout_id).FirstOrDefault();

Using find will only work when searching on the primary key, when you are wanting to search on other fields you will need to use Linq as shown above.

Then update it:

OldInsObj.booked = 1;

Finally, you can save your work to the database:

db.SaveChanges();
Sign up to request clarification or add additional context in comments.

4 Comments

i am getting exception type System.ArguementException ocured in EntityFramework.dll but was not handled in user code at -- var OldInsObj = db.SEATPLAN.Find(seat_id,layout_id);
@rakshi I've updated the code, I didn't realise you weren't searching on the primary key. You'll need to use Linq instead of .Find()
sir can u please tell me how can i use Linq here
@rakshi Linq is quite a big subject, if you let me know what it is you want to do that would help! I've updated my answer to use Linq to get the seat out of the database. It's this part specifically: .Where(s => s.seat_id == seat_id && s.layout_id == layout_id).FirstOrDefault();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.