Click here to Skip to main content
16,021,687 members
Articles / Web Development / ASP.NET

CRUD (Create, Read, Update, Delete) Operation With Generic List

Rate me:
Please Sign up or sign in to vote.
4.88/5 (26 votes)
27 May 2010CPOL2 min read 75.5K   1.3K   68   13
CRUD (Create, Read, Update, Delete) Operation With Generic List

Introduction

Data Table in conjunction with dataset is a very common option for CRUD (Create, Read, Update and Delete) operation towards database interaction.This is true that data table is developer friendly and provides cool features but at the same time this is heavy, resource hungry and not object oriented. As a result, we can think of Generic List LIST<T> as an introductory alternative of datatable and moving forward we will try to create a framework to provide the above CRUD functionality.

See below for the screen developed with the above framework.

Image1.JPG

A generic list is useful for creating a collection of similar objects. Generic List<T> where T is the Business Object / Business Entity / etc., which can be further strongly typed.

For example, List<Employee> will allow only Employee instance to be added to the list.

In the following framework, we have added a custom wrapper on the top of List<T> for better readability.

C#
public class EntityCollection<T> : List<T>{}

EntityCollection<T> where T refers to Business Entity/Object. Following is the way to insert as many entities into collection.

C#
EntityCollection<userbo> objUserCollection = new EntityCollection<userbo>();
objUserCollection.Add(new UserBO (……));
objUserCollection.Add(new UserBO (……));

EntityCollection<cusbo> objCustCollection = new EntityCollection<cusbo>();
objUserCollection.Add(new CusBO (……));
objUserCollection.Add(new CusBO (……));

Implementing Search Feature

FindByExpression” custom method of EntityCollection provides facility to filter data depending upon the expression passed as parameter. Expression should be given in “Property=Value” format.

C#
EntityCollection<userbo> userCollection = UserData(); // All users
userCollection = userCollection.FindByExpression("Name=Jhon");

EntityCollection<cusbo> objCustCollection = CustomerData();// All Customers
objCustCollection = objCustCollection.FindByExpression("CustId=3451");

Let’s see the underlying logic of method “FindByExpression”:

C#
public static EntityCollection<t> FindByExpression<t> 
	(this EntityCollection<t> EntityCollection,string FindExpression)
{
  Expression objExpression = GetPropertyInfo(EntityCollection, FindExpression, '=');

  // Find all matches -- Lambda Expression
  IEnumerable<t> objEntityList   = EntityCollection.FindAll
	(objC => objExpression.PropertyInfo.GetValue(objC, null).ToString()
                   == objExpression.ExpressionPropertyVal);

   EntityCollection<t> objEntities = new EntityCollection<t>();

   // Create a new entity collection with matched item
   foreach (var objEntity in objEntityList) objEntities.Add(objEntity);

   return objEntities;
}

The getPropertyInfo() method returns metadata of find expression property and the value to be searched wrapped together in a class.

Afterwards, we are using FindAll method of generic LIST with lambda expression to find all the matches.

Implementing Sort Features

SortByExpression” custom method of EntityCollection provides the facility to sort data depending upon the expression passed as parameter. Expression should be given in “Property Desc/Asc” format.

C#
EntityCollection<userbo> userCollection = UserData(); 		// All users
userCollection = userCollection.SortByExpression ("Name"); 	// Asc order

EntityCollection<cusbo> objCustCollection = CustomerData();	// All Customers
objCustCollection = objCustCollection. SortByExpression ("CustId Desc");

Let’s understand the logic of “SortByExpression”:

C#
public static EntityCollection<t> SortByExpression
	<t>(this EntityCollection<t> EntityCollection,string SortExpression)
 {
   bool blnDescending = false;

   IEnumerable objEntityList;

   Expression objExpression = GetPropertyInfo(EntityCollection, SortExpression, ' ');

   blnDescending = SortExpression.ToUpper().Contains("DESC");

    // Sort in Desc order
    if (blnDescending) objEntityList = 
	EntityCollection.OrderByDescending
	(objX =>objExpression.PropertyInfo.GetValue(objX, null));
    // Sort in ASC order
    else objEntityList = EntityCollection.OrderBy
	(objX => objExpression.PropertyInfo.GetValue(objX, null));

  EntityCollection<t> objEntities = new EntityCollection<t>();

  // Create a new entity collection with sorted items
  foreach (var objEntity in objEntityList)  objEntities.Add(objEntity);

  return objEntities;
}

We are taking help of OrderBy/OrderByDescending method of generic LIST<t> sort order.

Implementing Delete Feature

DeleteByExpression” custom method of EntityCollection provides the facility to remove entity from collection depending upon the matches. Expression should be given in “Property=Value” format.

C#
EntityCollection<userbo> userCollection = UserData(); // All users
userCollection = userCollection.FindByExpression("Name=Jhon");

Let’s understand the logic of “DeleteByExpression”:

C#
public static EntityCollection<t> DeleteByExpression<t>
	(this EntityCollection<t> EntityCollection,string FindExpression)
{
 Expression objExpression = GetPropertyInfo(EntityCollection, FindExpression, '=');

 // Find all matches -- Lamda Expression
 IEnumerable<t>  objEntityList = EntityCollection.FindAll
	(objC =>objExpression.PropertyInfo.GetValue(objC, null).ToString()
                  == objExpression.ExpressionPropertyVal);
 // Remove the matches from entity list
 foreach (var objEntity in objEntityList) EntityCollection.Remove(objEntity);

 return EntityCollection;
}

We are using FindAll method of generic LIST and eliminating the matches.

History

  • 27th May, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Reputed MNC in Kolkata
India India
Bibhas has 8 years of extensive experience in application development with exposure to business requirement study, system analysis and designing, coding ,testing,
implementation, end user training and client Interaction.

He was the part of application development team and worked for industry leading organizations like "ConocoPhillips", "Abbey National Bank" and “DHL".

Posses sound experience as a technical architect and all part of software development lifecycle.

His interest includes in Microsoft Technologies (ASP.NET 3.5 & SQL Server), Design Pattern and wide variety of internet technologies like AJAX, JQUERY etc.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Renju Vinod1-May-13 21:26
professionalRenju Vinod1-May-13 21:26 
GeneralMy vote of 3 Pin
SNathani12-Nov-10 16:21
SNathani12-Nov-10 16:21 
GeneralMy vote of 5 Pin
sharma rahul6-Aug-10 9:39
sharma rahul6-Aug-10 9:39 
GeneralMy vote of 5 Pin
moparthisai6-Aug-10 3:00
moparthisai6-Aug-10 3:00 
GeneralTYPO ERROR Pin
Sunil Wise3-Jun-10 5:42
professionalSunil Wise3-Jun-10 5:42 
Hi Paul,
You got my 5 for this article.
But i found Type Error (Which is common for every Programmer) in your article at the bottom

under "Implementing Delete Feature:"
You have given
EntityCollection userCollection = UserData(); // All users
userCollection = userCollection.FindByExpression("Name=Jhon");


which should be
EntityCollection userCollection = UserData(); // All users
userCollection = userCollection.DeleteByExpression("Name=Jhon");

Ragards,
SunilWise

Generalok article Pin
Donsw31-May-10 17:24
Donsw31-May-10 17:24 
GeneralI'm not sure I see the point Pin
Jeff Bowman31-May-10 12:41
professionalJeff Bowman31-May-10 12:41 
GeneralRe: I'm not sure I see the point Pin
MR_SAM_PIPER31-May-10 13:49
MR_SAM_PIPER31-May-10 13:49 
GeneralRe: I'm not sure I see the point Pin
Toli Cuturicu10-Aug-10 6:13
Toli Cuturicu10-Aug-10 6:13 
GeneralRe: I'm not sure I see the point Pin
Jeff Bowman10-Aug-10 10:42
professionalJeff Bowman10-Aug-10 10:42 
GeneralRe: I'm not sure I see the point Pin
SNathani12-Nov-10 16:20
SNathani12-Nov-10 16:20 
GeneralExcellent! Pin
RAND 45586627-May-10 20:11
RAND 45586627-May-10 20:11 
GeneralI love this good job! Pin
louislong27-May-10 4:29
louislong27-May-10 4:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.