simplify this complex world

August 5, 2011

Generic method for CRUD database using LINQ C#

Filed under: Catatan Oprekan — effendisusanto @ 3:09 am

Before all of you move forward read this posting, please ensure that you understand what is generic method in C#.

Ok, let’s move on. When dealing with database, we’re almost certainly dealing with CRUD < Create, Read, Update, Delete >. Therefor, if we can make a generic method code to handle CRUD for any table, we’ll get lot’s of advantage.
The first Generic method we want to explain first is Create < or Insert in database term >,

        public static void Insert<TClass> (TClass item) where TClass :class
        {
            using (var dc = new ApotekDataContext())
            {
                var table = dc.GetTable();
                table.InsertOnSubmit(item);
                dc.SubmitChanges();
            }
        }

The second generic method is Read < or Select in database term >, we separate method for select into 2 method,
SELECTALL and SELECTBYID. Let’s view our SELECTALL method

public static List<TClass> SelectAll() where TClass:class
{
     using(var dc=new ApotekDataContext())
     {
          var table = dc.GetTable().ToList();
          return table;
     }
}

so simple isn’t it. Before we move to the SELECTBYID, let’s imagine what is the complexity of SELECTBYID method.
The trap of this method is “how to get the ID/primaryID”. If we pass this trap, everything will be fine.

public static TClass SelectById<TClass,TId>(TId primaryKey) where TClass : class
{
     using (var dc = new ApotekDataContext())
     {
          var table = dc.GetTable();
          var modelMap = table.Context.Mapping;
          var dataMembers = modelMap.GetMetaType(typeof(TClass)).DataMembers;

          //Get the primary key field name
          var pk = (dataMembers.Single(m => m.IsPrimaryKey)).Name;
          var t = (from selected in table
               where
               selected.GetType().GetProperty(pk).GetValue(selected, null).ToString()==primaryKey.ToString()
               select selected).SingleOrDefault();
          return t;
     }
}

Weks.. time to work.. we have to go, we’ll add the method for update and delete later. Thanks

3 Comments »

  1. Still no comments yet.

    Comment by Chipi — January 29, 2013 @ 1:40 pm | Reply

  2. And no like too !

    Comment by Chipi — January 29, 2013 @ 1:40 pm | Reply

    • Life is unfair

      Comment by Poupa — January 29, 2013 @ 1:42 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.