Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top