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
Why would anyone use the chunk of code that I posted then ?
Can I use this with DDL ?
Craig Wagner
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.
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.
Why would anyone use the chunk of code that I posted then ?
Can I use this with DDL ?