Currently I’m working on a project’s data layer code. I’ve chosen LINQ to SQL for this purpose and created a helper library to perform CRUD operations in an easy and generic way.
Following is the code which insert any database object using LINQ:
1: public static void Insert<T>(T entityData) where T : class
3: using (TransactionScope trans = new TransactionScope())
5: using (App_Data.DBDataContext db = new App_Data.DBDataContext())
Few noteworthy points:
- I’m using transaction scope but we can omit that, because for single update or insert, LINQ already provides transaction support. This is only required while making multiple inserts or updates
- Conditional generics are used because GetTable<T>() requires T to be a reference type
- Just like above method, update and delete can also be implemented
- Suppose you have a database table Order
- In LINQ to SQL, this table is represented as a class, in which table columns are represented as properties
- To insert a new record for Order
- Create new object of Order – Order orderNewObject = new Order();
- Fill orderNewObject properties with desired values
- Pass this new object to Insert method like this - Insert<Order>(orderNewObject);
Using above method we can easily perform database operation without even writing a single T-SQL statement.