Deepak Deepak - 25 days ago 8
ASP.NET (C#) Question

C# - Object value is being lost

I'm trying to put my object into another by this method:-

for (int i = 0; i < NewTblList.Count; i++)
{
var ItObj = NewTblList[i];

InternShip It = new InternShip();
It.Name = NewTblList[i].Name;
It.Amount = NewTblList[i].Amount;
It.CreatedDate = NewTblList[i].CreatedDate;
It.Descr = NewTblList[i].Descr;
It.Duration = NewTblList[i].Duration;
It.ExpiryDate = NewTblList[i].ExpiryDate;
It.StartDate = NewTblList[i].StartDate;

It = db.Interns.FirstOrDefault(x => x.ID == ItObj.ID);
results = UtilityMethods<InternShip, int>.EditEntity(db, It);
}


My problem is that in this line of code:-

It = db.Interns.FirstOrDefault(x => x.ID == ItObj.ID);


My 'It' value is lost. I can't figure out what I'm doing wrong. PLease HELP!!

Answer Source

You are overwriting your It with whatever is present in the Interns database for the Id, ItObj.ID.

So you need to change it to:

foreach (var internship in NewTblList)
{
    // get the existing internship from the database
    InternShip It = db.Interns.FirstOrDefault(x => x.ID == internship.ID);

    // update the values from your list
    It.Name = internship.Name;
    It.Amount = internship.Amount;
    It.CreatedDate = internship.CreatedDate;
    It.Descr = internship.Descr;
    It.Duration = internship.Duration;
    It.ExpiryDate = internship.ExpiryDate;
    It.StartDate = internship.StartDate;

    results = UtilityMethods<InternShip, int>.EditEntity(db, It);
}