Link to home
Start Free TrialLog in
Avatar of Dodsworth
Dodsworth

asked on

LinqToSQL Update

I'm using the code below to update a record in a SQLCE database.  It seems strange that I have to fetch the record before I update it ?

     Using db = New sContext(ConnectionString)
                'find record
                Dim q = From s In db.Spots _
                Where s.sId = iId _
                Select s

                If q.Count() = 1 Then
                    Dim sp As SpotClass = (From s In db.Spots _
                        Where s.sId = iId _
                        Select s).First()
                    sp.sActive = "False"
                    sp.sEndDate = DateTime.Now.ToUniversalTime
                    db.SubmitChanges()
                End If
 

Open in new window


How would I update multiple records like in SQL.

UPDATE TBLTASK SET COMPLETEDATE = NOW WHERE TASKTYPE = 'AUTO'

Open in new window


(I hope that the answer is not what I'm suspecting!)
ASKER CERTIFIED SOLUTION
Avatar of Craig Wagner
Craig Wagner
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Dodsworth
Dodsworth

ASKER

Really ?

Why would anyone use the chunk of code that I posted then ?

Can I use this with DDL ?
LINQ-to-SQL (and Entity Framework) are designed to work on one entity at a time. If you've got a form where you are presenting a single instance of an object, letting the user change the values, and then pushing those changes to the database it works very well. It even works well if you've got a list of objects because the DataContext (or ObjectContext in EF) will track which objects and which columns have changed an only issue the necessary SQL.

However, if you want to do a bulk operation (e.g. update all rows that meet certain criteria, delete all rows that meet certain criteria) then LINQ-to-SQL and EF are the wrong tools. You could use them by retrieving a set containing all the objects you want to update, looping through the set and changing each one, then issuing SubmitChanges. The problems with that are that a SQL UPDATE will be issued for each changed object, so if you've got hundreds (or thousands) of objects that meet the criteria it will be incredibly inefficient vs. a single UPDATE statement and each UPDATE is performed in its own transaction instead of a single larger transaction.
Can I use it to send DDL commands ?
I'm not sure. In theory it should work if you sent a DDL statement through ExecuteCommand but it would probably be quicker just to throw a test together and try it. You've already got the DataContext and everything set up, it should only take a minute to try something simple. It's also getting beyond the scope of the original question.