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.

   1: /// <summary>
   2: /// Updates the database with item.
   3: /// </summary>
   4: /// <typeparam name="T">Type of the item</typeparam>
   5: /// <param name="item">The item.</param>
   6: public static void UpdateDatabaseWithItem<T>(T item) where T : class
   7: {
   8:     var store = GetNewDataContext();
   9:     var table = store.GetTable<T>();
  10:     table.Attach(item);
  11:     store.Refresh(RefreshMode.KeepCurrentValues, item);
  12:     store.SubmitChanges();
  13: }
  16: /// <summary>
  17: /// Inserts the item into database.
  18: /// </summary>
  19: /// <typeparam name="T">Type of the item</typeparam>
  20: /// <param name="item">The item.</param>
  21: public static void InsertItemIntoDatabase<T>(T item) where T : class
  22: {
  23:     var store = GetNewDataContext();
  24:     var table = store.GetTable<T>();
  25:     table.InsertOnSubmit(item);
  26:     store.SubmitChanges();
  27: }


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.

Comments (2)
  1. Danny says:

    Good article.

    I used it and added my own functions for a generic Linq base BLL class.

    I added a thanks to my post…/linq-to-sql-generic-insert-update-delete

Comments are closed.

Skip to main content