Link to home
Start Free TrialLog in
Avatar of Member_2_1242703
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]
                }
            }

Open in new window

Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Hi Mike;

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.
Avatar of Member_2_1242703
Member_2_1242703

ASKER

This is the error I'm getting:

"New transaction is not allowed because there are other threads running in the session."

Open in new window

Please post the schema of the database table PTO_REQUEST. Thanks
ID int (primary key, is identity)
Status VarChar (50)
Hours Decimal (5, 2)
EMPLID char(11)
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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();
                    }                                       
                }}

Open in new window

Very good Mike, have a great day.