0

I am facing a problem when try to update records via using 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. If I want to update the first 5 records, what should I do?

DragonZelda
  • 168
  • 1
  • 2
  • 12

3 Answers3

1
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

TGH
  • 38,769
  • 12
  • 102
  • 135
1
db.Pins.Where(EPin => EPin.UserID == null && EPin.CC == 5000).Take(5).ToList()
       .ForEach( item =>  { item.OrderID = OrderID; item.UserID = intUserID; });
db.SaveChanges();
Damith
  • 62,401
  • 13
  • 102
  • 153
0

If you using EF6 then you can use 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

jolySoft
  • 2,948
  • 2
  • 30
  • 34