简体   繁体   English

使用Linq将数据库更新为实体

[英]Updating Database with Linq to Entities

I can add to, and remove from a Database table with Linq to Entities. 我可以使用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. 我已经搜索了Stack Overflow,并尝试了《答案》和Google上提供的各种示例,但是它们几乎都是相同的,并且没有帮助。

You basically need to retrieve the entity (record) itself and not just the property (column) to be able to update it through EF: 基本上,您需要检索实体(记录)本身,而不仅仅是属性(列),以便能够通过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();

Here's @Xander's answer using Lambda's 这是@Xander使用Lambda的答案

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 :) 我知道您说您对他有误,这更多是出于教育目的:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM