Visual Studio 2008 RTM Changes to LINQ to SQL
Posted
Wednesday, December 19, 2007 2:44 PM
by
Nathan Zaugg
For those who haven't heard Visual Studio 2008 has officially been released! That also means that the .net Framework 3.5 has also been released! For those who have done the Beta's there is a couple of method renaming that has happened that will break your bits!
Summary
- To add a record .Add and .AddAll has been replaced with .InsertOnSumbit and .InsertAllOnSubmit on your Linq Table.
- To delete a record .Remove and .RemoveAll have been replaced with .DeleteOnSubmit and .DeleteAllOnSubmit on your Linq Table.
I think I can understand why they made the change. When you had a line that looked like "dbContext.Documents.Add( mydoc );" it never really felt like I was inserting a record into my database (in fact you are not inserting, not yet! Not until you call .SubmitChanges(); on the DataContext. The same goes for the delete. It was never clear if LINQ was going to "notice" the new record and make sure it is properly added to the database.
So here are are some Linq Samples that we all love!
// Insert a new Record
ADCDataContext db = new ADCDataContext();
Document d = new Document() {
Description = "This is a doc",
FileType = "doc",
CreatedDate = DateTime.Now
};
db.Documents.InsertOnSubmit( d );
db.SubmitChanges();
int did = d.ID; // Notice how the document we just added has been updated.
// Updating a record (or multiple)
ADCDataContext db = new ADCDataContext();
Document doc = (from d in db.Documents
where d.ID == 551
select d).Single();
doc.ModifiedDate = DateTime.Now;
db.SubmitChanges();
// Delete a record (or multiple)
ADCDataContext db = new ADCDataContext();
var doc = from d in db.Documents
where d.CreatedDate > DateTime.Now.AddDays(-90)
select d;
db.Documents.DeleteAllOnSubmit(doc);
db.SubmitChanges();
// Many Custom Type :: Select many documents but return specific type
List<Notifications> changeNotifications = (from doc in db.Documents
where doc.CreatedDate > DateTime.Now.AddMonths(-1) ||
doc.ModifiedDate > DateTime.Now.AddMonths(-2)
select new Notification()
{
NotificationType = ChangeNotificationTypeEnum.All,
NotificationDate = doc.ModifiedDate ?? doc.CreatedDate,
Text = doc.Title
}).ToList();