I need a LINQ procedure to fulfill the following need:
I need to add a record if the record does not exists in the data base table or It should update the records if the record does exists in the table in this case procedure only update the record if the record has any changes only.I have done it but feel it can be enhanced by reducing code,
private static void AddNewItem(SPListItem transportDetails)
{
try
{
DataClassesDataContext dc = new DataClassesDataContext();
if (!dc.TransportDetails.Where(u => u.GuId == transportDetails.ID).Any())
{
WriteToEventLog("In the AddNewItem block....", EventLogEntryType.Information);
WriteToEventLog("Start to add new Item....", EventLogEntryType.Information);
var transport = new TransportDetail
{
Request_Date = (transportDetails["Request Date"] != null) ? Convert.ToDateTime(transportDetails["Request Date"].ToString()) : DateTime.MinValue,
Time_of_Travel = (transportDetails["Time of Travel"] != null) ? transportDetails["Time of Travel"].ToString() : string.Empty,
};
dc.TransportDetails.InsertOnSubmit(transport);
WriteToEventLog("Process of adding new Item....", EventLogEntryType.Information);
dc.SubmitChanges();
WriteToEventLog("New Item added....", EventLogEntryType.Information);
}
else
{
WriteToEventLog("Start to update the item....", EventLogEntryType.Information);
TransportDetail oldTransportDetails = dc.TransportDetails.Single(u => u.GuId == transportDetails.ID);
oldTransportDetails.Request_Date = (transportDetails["Request Date"] != null) ? Convert.ToDateTime(transportDetails["Request Date"].ToString()) : DateTime.MinValue;
oldTransportDetails.Time_of_Travel = (transportDetails["Time of Travel"] != null) ? transportDetails["Time of Travel"].ToString() : string.Empty;
dc.SubmitChanges();
WriteToEventLog("The item updated....", EventLogEntryType.Information);
}
}
catch (Exception ex)
{
WriteToEventLog(ex);
}
}
Thanks, Vimal