简体   繁体   English

DBSet如何多次更新?

[英]DBSet how to multiple update?

I am facing a problem when try to update records via using dbset. 尝试使用dbset更新记录时遇到问题。 The following is my code: 以下是我的代码:

CROPContext db = new CROPContext();

var EPins = from EPin in db.Pins.Take(5)
            where
                (EPin.UserID == null && EPin.CC == 5000)
            select EPin;

foreach (var item in Epins.ToList())
{
    item.OrderID = OrderID;
    item.UserID = intUserID;
}
db.SaveChanges();

When I update the records, it update all records. 当我更新记录时,它会更新所有记录。 Then I check the number EPins.Count(), I find out that it is not 5 but the number of all. 然后我检查数字EPins.Count(),我发现它不是5而是所有的数量。 If I want to update the first 5 records, what should I do? 如果我想更新前5条记录,我该怎么办?

var EPins = (from EPin in db.Pins
            where
                (EPin.UserID == null && EPin.CC == 5000)
            select EPin).Take(5);

foreach (var item in Epins.ToList())
{
    item.OrderID = OrderID;
    item.UserID = intUserID;
}
db.SaveChanges();

Try the above 试试以上

db.Pins.Where(EPin => EPin.UserID == null && EPin.CC == 5000).Take(5).ToList()
       .ForEach( item =>  { item.OrderID = OrderID; item.UserID = intUserID; });
db.SaveChanges();

If you using EF6 then you can use EntityFramework.Extended: 如果您使用EF6,那么您可以使用EntityFramework.Extended:

db.Pins.Where(EPin => EPin.UserID == null && EPin.CC == 5000)
       .Update(p => new Pin { OrderID = OrderID; UserID = intUserID; });

Avoid using .ForEach because of performance implications, stream the data rather than materialise it 避免因为性能影响而使用.ForEach ,流式传输数据而不是实现它

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

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