Arrow
Arrow

Reputation: 2904

Updating Database with Linq to Entities

I can add to, and remove from a Database table with Linq to Entities. However the following code will not update the database. (There are no exceptions, or anything - it just doesn't update.):

        // Change box qty
        var pnumber = Request.Form["PartNumber"];
        var oid = Session["OOID"];
        var uid = WebSecurity.CurrentUserId;
        var newqty = Request.Form["Quantity"];
        var c = (from item in database.Carts
                           where item.UserId == 
                           uid && item.PartNumber == 
                           pnumber && item.OrderId == (string)oid
                           select item.Boxes).FirstOrDefault();
        c = newqty.AsInt();
        database.SaveChanges();
        Response.Redirect("~/Protected/Account/Shopping/Cart");

Any ideas what I may be doing wrong, or how to resolve this? I've searched Stack Overflow and tried various samples provided in the Answers, and also on Google, but they're all pretty much the same, and haven't helped.

Upvotes: 1

Views: 426

Answers (2)

Eonasdan
Eonasdan

Reputation: 7765

Here's @Xander's answer using Lambda's

var newqty = Request.Form["Quantity"]; 
var c = database.Carts.Where(x => x.UserId == 
           uid && x.PartNumber == 
           pnumber && x.OrderId == (string)oid).FirstOrDefault();
c.Boxes = newqty.AsInt();
database.SaveChanges();

I know you said you got an error with his, this is more for you educational purposes :)

Upvotes: 1

Alex
Alex

Reputation: 35399

You basically need to retrieve the entity (record) itself and not just the property (column) to be able to update it through EF:

var newqty = Request.Form["Quantity"]; 
var c = (from item in database.Carts
           where item.UserId == 
           uid && item.PartNumber == 
           pnumber && item.OrderId == (string)oid
           select item).FirstOrDefault();
c.Boxes = newqty.AsInt();
database.SaveChanges();

Upvotes: 5

Related Questions