As long as there is an active instance of the DataContext class to track changes, LINQ to SQL will happily insert/update/delete rows in an associated table everytime objects in the collection that maps the relationship in the model are modified, and the DataContext.SubmitChanges() method is called.
For example:
using (var db = new DataContext())
{
var person = db.Persons.Where(p => p.Name == "Foo").SingleOrDefault();
if (person != null)
{
// Inserts a new row in the 'PersonCategory' table
// associated to the current 'Person'
// and to the 'Category' with name 'Employee'
person.PersonCategories.Add(new PersonCategory() { CategoryName = "Employee" });
// Updates the 'CategoryName' column in the first row
// of the 'PersonCategory' table associated to the current 'Person'
person.PersonCategories(0).CategoryName = "Consultant";
db.SubmitChanges();
}
}
Things are a little different if you are making changes to the model objects in "disconnected" mode, that is when the DataContext instance that was used to initially create those objects no longer is around.
In this case insert/delete operations on associated tables will work just fine when the object having the modified collection is attached to a new DataContext with the Table(TEntity).Attach method, followed by DataContext.SubmitChanges().
However, modifications on any of the existing objects in the collection will not automatically be applied in the associated table. In order to do that, you must manually call the Table(TEntity).Attach method for each object in the collection.
Here is a quote from the MSDN documentation:
When a new entity is attached,
deferred loaders for any child
collections (for example, EntitySet
collections of entities from
associated tables) are initialized.
When SubmitChanges is called, members
of the child collections are put into
an Unmodified state. To update members
of a child collection, you must
explicitly call Attach and specify
that entity.
Here is a concrete example:
// The 'Person' object has been detached
// from the originating 'DataContext', which is now disposed
person.PersonCategories.Add(new PersonCategory() { CategoryName = "Employee" });
person.PersonCategories(0).CategoryName = "Consultant";
using (var db = new DataContext())
{
// Will detect added and deleted objects
// in the 'PersonCategory' collection
db.Person.Attach(person);
// Required to detect and modifications
// to existing objects in the 'PersonCategory' collection
foreach (var personCategory in person.PersonCategories)
{
db.PersonCategory.Attach(personCategory);
}
db.SubmitChanges();
}