1

I'm reading data from an XLS document, and I'm using the superb LINQ to Excel library. The problem I have is more of a problem with dealing with LINQ.

I read new and updated incidents from an excel sheet. So I want check if the incident already exists in the database, and if it does I want to hook it up with that incident and then update it with all the new data from the excel that I've read. Some code:

var excel = new ExcelQueryFactory("filepath");

var getincident = from jj in excel.Worksheet<Incident>("Sheet1")
                  select jj;

foreach (var incident in getincident)
{
    if (incident.CallId.Trim() == "")
        break;
    if (exists(incident.CallId, context))
    {
        incident.id = (from b in context.Incidents
                       where b.CallId == incident.CallId
                       select b.id
                      ).First();
        context.Incidents.Attach(incident, true);
    }
    else
    {
        context.Incidents.InsertOnSubmit(incident);
    }

    context.SubmitChanges();

}

and the exists is a simple check if the incident exists:

private bool exists(string piCallId, DataClasses1DataContext context)
{
    return (from b in context.Incidents
            where b.CallId == piCallId select b
           ).Any();
}

I need some way first to check if the incident exists before all the new data is added, and then submit the changes. Please help.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Fore
  • 5,726
  • 7
  • 22
  • 35
  • I don't quite understand your problem? Does your exist method not already check to see if the incident exists and you are calling this before the the Insert/Attach? – sgmoore Nov 13 '10 at 16:51
  • It works fine to check if the incident exists. The problem I'm having is how I should update the existing incident in the database. I would like to first get the object from db, and then add all the new properties and then submitchanges, but I cant do that, since in the foreach loop holds all the new values that I want to update the existing Incident with, I hope you understand what I mean. – Fore Nov 13 '10 at 16:55

1 Answers1

0

Does this do what you want?

var existingIncident = 
    (from b in context.Incidents
     where b.CallId == incident.CallId
     select b
     ).SingleOrDefault();

 if (existingIncident != null)
 {
      existingIncident.xxx = incident.xxx;
      existingIncident.yyy = incident.yyy;
      ...
 }
 else
    context.Incidents.InsertOnSubmit(incident);
sgmoore
  • 15,694
  • 5
  • 43
  • 67