if record exists update else insert using LINQ

I have an xml file that I parse and insert into the database. What I want to do is, if the records in the xml file already exist in the database I just want to update the database, If they don't exist I would like to insert them. I would like to do this as efficiently as possible either through LINQ and/or stored procedures, but can't find anything online. The xml file has IDs that correspond to database IDs.

Running ASP.NET 3.5 and MS Server 08

Who is Participating?
naspinskiConnect With a Mentor Commented:
If you want to use linq:
//instead of this foreach<int> you will do a foreach<XElement> or something else to run through your xml entries
//Also, you will obviously have to change my item class to what you want
foreach (int xmlID in xmlEntries)
        item i = (from p in db.items where p.itemID == xmlID select p).First();
        //it is present in the database -- now edit it
        //it wasn't there, so insert it

Open in new window

Guy Hengel [angelIII / a3]Billing EngineerCommented:
if you use SQL 2008, you should learn up the newly introduce MERGE statement:
idsnewsAuthor Commented:
Thanks, but from the looks of it the MERGE statement is only useful for merging tables. Whereas I need to merge a table with an XML document.
Guy Hengel [angelIII / a3]Connect With a Mentor Billing EngineerCommented:
with SQL Server, using XML means using OPENXML() function to get a table-valued output from XML input.
as from SQL 2005, you could also use the xml data type, and perform XQuery on that to again have "table" data.

once you have that, the MERGE can be brought into play ...
idsnewsAuthor Commented:
Thanks angelll for the MERGE solution but it seekemed a little over my head and the try catch with the LINQ was exactly what I was looking for because I was already parsing the XML file using linq and XElements
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.