Insert and delete with LINQ to SQL

Needed to remove all old posts associated with a specific user and then add new posts. With a DataSet, this could be done by fetching the data, clear it and then add the new posts. A simular way is possible in LINQ-to-SQL:
CalendarDataContext db = new CalendarDataContext();
List<int> categories = new List<int>() // ..with some data of course

// Get current posts
IQueryable<SubscriptionSetting> settings = db.SubscriptionSettings.Where(s => s.UserId == username);

// Delete all old posts
db.SubscriptionSettings.DeleteAllOnSubmit(settings);

// Add new
foreach (int c in categories) {
db.SubscriptionSettings.InsertOnSubmit(new SubscriptionSetting() { UserId = username, CategoryId = c });
}

db.SubmitChanges();

Related posts:

Comments

comments powered by Disqus