KyloRen
KyloRen

Reputation: 2741

Update database via LINQ

For the life of me I cannot get get LINQ to actually update a record set. At the present moment all I am succeeding in doing is adding a new row to the database.

To explain the code below, I am looping through a column witch holds dates. filterFrom is the date to start the foreach loop and filterTo the end date in the loop. All which is done through the DateRange method. If code for that is needed please say so, but the foreach loop itself is working the way it should.

Then what I am trying to do is test to see if the date for the record set exists via LINQ, p.Date_Data == day and if columns p.Time_Data_2 and p.Time_Data_1 are not null values ,to then update the column Info_Data. However what is happening is that I am adding a new row with just the the data from the query and not updating the existing data.

foreach (DateTime day in DateRange(filterFrom, filterTo))
{
    if (sql.Staff_Time_TBLs.Any(p => p.Date_Data == day && p.Staff_No == SelectedEmployee && p.Time_Data_1 != null && p.Time_Data_2 != null && p.Info_Data == null))
    {    
        Staff_Time_TBL updateRow = new Staff_Time_TBL
        {                            
            Info_Data = "myValue",                            
        };    
        sql.Staff_Time_TBLs.InsertOnSubmit(updateRow);
    }
    sql.SubmitChanges();
}

How could I amend this so that it updates the data and not create a new row of data in the database?

Upvotes: 0

Views: 94

Answers (1)

Dan Dumitru
Dan Dumitru

Reputation: 5333

You are checking if the record exists, but you should also try to retrieve it in order to update it, so you should use FirstOrDefault instead of that Any.

var staffTime = sql.Staff_Time_TBLs.FirstOrDefault(p => p.Date_Data == day && 
    p.Staff_No == SelectedEmployee && p.Time_Data_1 != null && p.Time_Data_2 != null &&
    p.Info_Data == null);

if (staffTime != null)
{
    staffTime.Info_Data = "myValue";
    sql.SubmitChanges();
}

Upvotes: 1

Related Questions