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
8: var store = GetNewDataContext();
9: var table = store.GetTable<T>();
11: store.Refresh(RefreshMode.KeepCurrentValues, item);
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
23: var store = GetNewDataContext();
24: var table = store.GetTable<T>();
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.