Generic Insert and Update for LINQ To SQL

Quick code snippet time!

The following are generic methods for inserting and updating a detached entity into a database using LINQ to SQL.

/// <summary>
/// Updates the database with item.
/// </summary>
/// <typeparam name=”T”>Type of the item</typeparam>
/// <param name=”item”>The item.</param>
public static void UpdateDatabaseWithItem<T>(T item) where T : class
{
    var store = GetNewDataContext();
    var table = store.GetTable<T>();
    table.Attach(item);
    store.Refresh(RefreshMode.KeepCurrentValues, item);
    store.SubmitChanges();
}
 
 
/// <summary>
/// Inserts the item into database.
/// </summary>
/// <typeparam name=”T”>Type of the item</typeparam>
/// <param name=”item”>The item.</param>
public static void InsertItemIntoDatabase<T>(T item) where T : class
{
    var store = GetNewDataContext();
    var table = store.GetTable<T>();
    table.InsertOnSubmit(item);
    store.SubmitChanges();
}

GetNewDataContext() is a method (not shown) which does what its name says, returns a data context.

The only part that is not really obvious is on line 11. That line is a “hack” to allow you to attach an entity as modified without using a timestamp or turning off optimistic concurrency or attaching a previous version of the entity.  What this means is that this update will throw a fit if there is a concurrency error!  However, for my use of this code ( mainly for unit test preparation ) it works great.