Member_2_1242703
asked on
Updating a single record in forEach using C#/Entity
Is there any way I can update a record after doing something in a for each? This is the idea (in bold), but doesn't work.
using (var db = new PTO_SystemEntities())
{
var pto = db.PTO_REQUEST
.Where(q => q.Status != "Cancelled" && q.Status != "Processed" && q.Type != "Reverse Leave");
foreach (var i in pto)
{
Console.Write(i.EMPLID.Trim() + ", " + location.Trim() + ", " + jobcode.Trim() + ", " + i.Hours + Environment.NewLine);
[b] db.Entry(i).Property(e => e.Status).CurrentValue = "Processed";
db.Entry(i).Property(e => e.Status).IsModified = true;
db.SaveChanges();[/b]
}
}
ASKER
This is the error I'm getting:
"New transaction is not allowed because there are other threads running in the session."
Please post the schema of the database table PTO_REQUEST. Thanks
ASKER
ID int (primary key, is identity)
Status VarChar (50)
Hours Decimal (5, 2)
EMPLID char(11)
Status VarChar (50)
Hours Decimal (5, 2)
EMPLID char(11)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Yup, was just coming on to post my solution...
using (var db = new PTO_SystemEntities())
{
var pos = db.PTO_REQUEST
.Where(q => q.Status != "Cancelled" && q.Status != "Processed" && q.Type != "Reverse Leave");
foreach (var i in pos)
{
//whatever code here
using (var dd = new PTO_SystemEntities())
{
dd.PTO_REQUEST
.Where(q => q.ID == i.ID)
.ToList()
.ForEach(a => a.Status = "Processed");
dd.SaveChanges();
}
}}
Very good Mike, have a great day.
You state the following, "This is the idea (in bold), but doesn't work.", how does it not work, do you get a run time error or compile error or something else?
Please also post the schema of the PTO_REQUEST table from the database.