Home > Enterprise >  Updating fields after SubmitChanges in C# using foreach loops
Updating fields after SubmitChanges in C# using foreach loops

Time:09-30

I have a project that I am working on, which is related to the work of daily shifts for employees, so that I have made the code for filling in the dates and their days in the relevant table ResultTB as follows and it's work correctly

var dt1 = DateTime.Parse(txtFromDate.Text);
var dt2 = DateTime.Parse(txtToDate.Text);

var dt = DateTime.Parse(txtFromDate.Text);

if (dt <= dt2)
{
    dt = dt.AddDays(-1);

    while (dt2 >= dt1)
    {
        List<ResultTB> ResultList = new List<ResultTB>
                    {
                        new ResultTB{NameOfDay = dt1.DayOfWeek.ToString(),DateOfDay = dt=dt.AddDays(1) }
                    };

        foreach (var item in ResultList)
        {
            dt1 = dt1.AddDays(1);
            db.ResultTBs.InsertOnSubmit(item);
        }

        db.SubmitChanges();

        DGVResult.DataSource = db.ResultTBs.ToList();
    }
}

Now I would like to make an update to the table ResultTB to columns EmpName EmpID from EmployeeTB, so that the code searches in the table EmployeeTB which have the status of the employee “possible” and assigns it to a date in order, and this is the code that I wrote, but it adds the first person in the EmployeeTB table and assigns it to all the dates in the table ResultTB.

var EmpList = db.EmployeeTBs
                .Where(x => x.EmpStatus == "possible").ToList();

foreach (var EmpItem in EmpList)
{
    var ListOfResult = db.ResultTBs.Where(r => r.EmpName == null).ToList();

    foreach (var itemResult in ListOfResult)
    {
        itemResult.EmpID = EmpItem.EmpID;
        itemResult.EmpName = EmpItem.EmpName;
    }

    db.SubmitChanges();
}

I tried many solutions but it didn't work with me please help me to solve this problem. Thanks

CodePudding user response:

var EmpList = db.EmployeeTBs.Where(x => x.EmpStatus == "possible").ToList();

for (int i=0; i< EmpList.length; i  )
{
    var ListOfResult = db.ResultTBs.Where(r => r.EmpName == null).ToList();

    ListOfResult[i].EmpID = EmpList[i].EmpID
    ListOfResult[i].EmpName = EmpList[i].EmpName
}
db.SubmitChanges();

If I understood your question correctly this should work.

  • Related