Programming Training | New Way New Style
A Step-by-Step ASP.NET Tutorial for Beginners -
MAHAK: Society to Support Children, Suffering from Cancer
Read Valuable Verse From Cosmic References Quran & Bible

Data Access Layer

Mahsa Hassankashi | Tuesday 10 2015 15:2

Data Structure - Collection - Entity Framework - ADO.NET - LINQ - Methods

The most complete and best source about Data Access which provides almost all of concept in this domain, it just take ONE DAY to learn it (albeit if you have a bit experience about it)
I strongly suggest to read it and offer to others. Finally please leave your feedback and points to complete this source.

A Step-by-Step ASP.NET Tutorial for Beginners

This article explains:

Data Access Sample File  3,767 KB

Data Access forms the major of programming matters, in this article I will explain about it and expand its complexity by visualizing its concept!

For running a project you need to have application and database and in the middle stage you need to fetch data from database and provide a connection between App and Database, you should write some queries to make a bridge from app to DB in order to get data from DB and analyze on them (Insert, Delete, Update, Select) in App and eventually show them to users. This process needs a suitable Data Service plan according to your App and kind of your DB conditions.

The biggest challenge here is to choose the best and appropriate one.

Which one? LINQ to SQL? Entity Framework? ADO? NHibernate?

Before I dig into DataAccess concept, I prefere to overview on the common and popular Data Structures. It is so important to have a proper knowledge about "Collection" due to this issue you need to work with your data on application and store them on suitable container to move them into database or prepare them to show users.


Set or group of records which makes one meaningful unit:

In fetch and modification progress we need appropriate container to store them temporary in it. Appropriate container depends on:

1. Our action which we want to do on data ( just read, do modification such as insert, delete, etc )

 2. Number of records which should be transfer 


Collection Sample Code 495KB

Collection IEnumerable IList IQueryable ICollection Stack Queue Dictionary


1. Fixed Length ->  difficult to change the nember of count

2. Type Safe -> you determin its type at coding process (it has better performance due to do not consume time at run time to spesific type countainer )

3. Use “for” keyword to fill and iterate through array


1. It does not have spesific length -> It is possible to grow data , it is good feature because of at the first we are not likely to sure about length of collection

2. Arraylist does not have any spesific type and it will be determined at run time, its adbantage is when you are not sure about type of data untill in run time user detemines it, and its disadvantage is to reduce performance by consuming time , so use it just when you need it it is like var or object

3. Use “foreach” keyword for iterate through it



ArrayList and Object








Why we needList?

1. List  does not have spesific length à It is possible to have data without knowing its size , it is good feature because of at the first we are not likely to sure about length of collection.

2. List has Spesific type so it is strong type, therfore it has better perfomance and high speed in comparison with ArrayList and reduce unwanted error in compile time.

3.  Use “foreach” keyword for iterate through it.



Why we need IList? Ilist is an interface of list (does everything that List does) and to observe polymorphism in order to decouple and control on add or remove method that implement on the client side, everything else are similar to List. Whenever we want to change on some operation “IList” allow us to do that easily with at least changing in the whole of codes.

Ilist can not be instantiate from Ilist , so it should be instantiate from List

System.Collections.Generic.IList<string> strIList = new List<string>();

Difference between Abstract and Interface

1.Abstract inherit from just one class but Interface implements from one or more interfaces

2.Abstract can have non concrete method (expand method) but you have to define just signature inside interface

3.Inside Abstract class you can define variable and value but you are not allowed to define variable inside interface

4.An abstract class can have constructor but inside interface you are not allowed to define constructor

5.You can write scope for member of interface, red ones donot allow but blue one allow

Ilist is an interface and as I mentioned that how a class cannot be driven from two class it just can be driven from only one class, so whenever you want to drive from two class it is not possible to inherit from two abstract class but it is possible to drive from one class and another one Ilist as interface

Later in future you decide add some features on your class and inherit it from another class

So because of this reason we always prefer to use interface of collection so that if you want to change your code and enhance its abilities it is possible to grow it

On the otherhand interface keeps your program extensible and

Decouple: The classes are independent from each other error, exeption  and failur will happen rarly in future changing code

Polymorphism: When you are using interface you absolutly observe and do polymorphism and oop it means encapsulate your designer

Interface means a point or a node to join two part to eachother it means making low dependency from two part and make a joint section to make felxible chang in future





Generic Stack

Generic Queue

Entity Framework
Entity Framework vs ADONET

Entity Framework is an Object Relational Mapping (ORM). It is a bridge between domain object (business logic)  and ---> RDBMS is Relational DataBases Management Systems  that stores data as relational tables in spite of flat database are more flexible and structured.
EF provides an automated process to access (select) and maniplation (delete , insert, update) without writing too much code lines in Data Access Layer , in ADO.NET we had to write TSQL codes for everything we must do with DB { insert into table () values () } or {update table set field1=value1 ,...where ID=? } or {delete from table where ID=?} 
Assume you have many feilds and you have to write code manually for each inserting deleting and updating so it takes so much time.

EF includes three part: 
1. Domain Object   
2. Mapping Information  
3. Relational Database Object

Other ORM are : NHibernate, SubSonic and etc but EF is open source and flexible to change.

EF -> POCO class: Plain Old CLR Object: is simple class that define to store data regardless of type of Data Access Layer Technology (in MVC you create POCO in model folder)

EF Features:

1. Persistence Ignorance: POCO class never ever likes to know any information about Data 
Access Layer and dependencies. It is reusable to any web services , framework and etc...

2. Change Tracking: EF has this ability to detect changes in record that which changes have
 been changed and in savechanges method these changes will be stored in database.

3. LazyLoading: EF has this ability to load objects in the specific point that really we need them not as immediate as we instantiate one object and load all of that in memory just when call exactly their name method to load them. Assume we have Student POCO class and in this class we have the method so called LoadAddress() for Addresses properties when we instantiate Student stud= new Student();  their addresses will not be loaded whenever we call stud. LoadAddress() then it will loaded in memory.

Three approach to modeling EF:

1. Database First
2. Model First
3. Code First 

Entity Framework CodeFirst
Linq2Entity CodeFirst Sample Code 989KB

1. EF CodeFirst 

2. EF CodeFirst 

3. EF CodeFirst

4. EF CodeFirst

5. EF CodeFirst

6. EF CodeFirst

7. EF CodeFirst

8. EF CodeFirst 

9. EF CodeFirst

10. EF CodeFirst

11. EF CodeFirst

12. EF CodeFirst

13. EF CodeFirst

14. EF CodeFirst

15. EF CodeFirst

16. EF CodeFirst

17. EF CodeFirst

18.EF CodeFirst

19. EF CodeFirst

20. EF CodeFirst

21. EF CodeFirst

22. EF CodeFirst

23. EF CodeFirst

24. EF CodeFirst

25. EF CodeFirst

26.EF CodeFirst

Entity Framework ModelFirst
Linq2Entity ModelFirst Sample Code 493 KB

1. EF ModeFirst

2. EF ModelFirst

3. EF ModelFirst

4. EF ModelFirst

5.EF ModelFirst

6.EF ModelFirst

7. EF ModelFirst

8.EF ModelFirst

9.EF ModelFirst

10.EF ModelFirst

11.EF ModelFirst

12.EF ModelFirst

13.EF ModelFirst

14.EF ModelFirst

15.EF ModelFirst

16. EF ModelFirst

17. EF ModelFirst

18. EF ModelFirst

19. EF ModelFirst

20. EF ModelFirst

21. EF ModelFirst

22. EF ModelFirst

23. EF ModelFirst

24. EF ModelFirst

25. EF ModelFirst

26. EF ModelFirst

27. ModelFirts

28. EF ModelFirst

Entity Framework DatabaseFirst
 Linq2Entity DatabaseFirst Sample Code - 491 KB

1. EF DBFirst

2. EF DBFirst

3.EF DBFirst

4. EF DBFirst

5. EF DBFirst

6.EF DBFirst

7. EF DBFirst

8. EF DBFirst

9. EF DBFirst

10. EF DBFirst

11. EF DBFirst

12. EF DBFirst

13. EF DBFirst

14. EF DBFirst

15. EF DBFirst

  Entity Framework Sample Code - 639 KB   
DataAccess-Database 185 KB
LINQ: Language INtegrated Query vs SQL: Structure Query Language ->
SQL: so you just can make a query with RDBMS Database by SQL  While.....
LINQ:  (1): you can use linq with any database, array, collection, xml, object due to its instruction is unique and common it works for .NET >3.5
            (2): you can debug linq in runtime
            (3): linq is very flexible
I strongly recommend you to visit this link to enhance your abilities in writing code via Linq :  
101 Linq Sample  , Linq to Xml Sample
XML: EXtensible Markup Language , Describe Data , Flexible and Independent from Hardware and Software to carrying Information
HTML: HyperText Markup Language , Display Data
using: System.Collections.Generic; System.Linq; System.Text; System.Xml; System.Xml.Linq;


Linq2Array - Where

Linq2Array - Orderby

Linq2Array - Groupby
Linq2Array - Take The First Three Instance

Linq2Array - Method Expression



Linq2XML - Load XML file and query to it




Linq2XML - Create XML File and Save it and Query to it 

















 ADO.NET Sample Code - 5 KB
 ADO-Database 181 KB


DataReader - Simple Select - ExecuteReader

DataReader - Select with Where - ExecuteReader

Insert to table(field) values(value) - Executnonquery()


Delete from table where ID=? - Executenonquery()

Update table set feild=value where ID=? - Executenonquery()



DataAdapter - DataSet











Entity vs ADO.NET

We cannot underestimate ADO.NET and its high speed particularly when you need to change your provider in one application from one type database to another one. But as you see and know you are involved to define all of your fields from database and traverse among huge code lines. On the one hand absolutely these kind of tasks are boring for coder because of iterating manually same structure code for all of your tables in database confuse you and you make mistakes which are hard to tracking. But coders build Dapper.Net to make it easy for mapping object from business layer into relational database:

But the worst part of ADO is to learn specific language related to each kind of database, when you work with SQL Provide you should write your query in TSQL, if you want to use XML you should know XQuery and etc.

1. Assume you have huge database with many tables and fields as well, how to organize complex insert, delete, update and select.

2. Assume you have a lot of pages which should be filled and process on their data and you do not have too much time.

Assume your customer has different database except MS SQL.

In a nutshell ADO.NET is FAST, SAFE in runtime but time consuming and SLOW in developing. ADO is not ORM.
While Entity Framework is SLOW, less SAFE in runtime but FAST in developing, EF is ORM.
You can enhance EF via Stored Procedure and services to make it as qualified as ADO.

Lambda Expression
Lambda Expression is a style of writing method but in a summary way:
Method: public string NameClass (string argument1, integer argument2)
Lambda Expression: does not have (public, private,..), name class, return value 
1. Lambda save your time by preventing total section of method and to a short glance you get  what happend?

string[] strArray = new string[3] { "Mahsa", "Hassankashi", "Hossein" };

var query = strArray.First( n => n[0] == 'M');

{ n } => { n[0] == 'M'  }

{ n } is input parameter without declaration you just write a letter which can be your parameter , it should be same as on the next side of arrow

{ n[0] == 'M' } is expression section which defines your operation, here this expression select words which the first letter begins from 'M'

Partial Methods
Partial methods are useful when one class is separeted into two or more, due to one section would be modifed commonly but another section is almost fixed without changing. Finally both part will compile as one.

One class is:

partial class Demo
public static void Demo1()
//do some operations ...

Another class is:

partial class Demo
public static void Demo2()
//do some different operations...

Above class will be built in different class you should pay close attention that partial is keyword "Demo" should be same in both of them but Demo1 and Demo2 are different.

When these application compiled both class would be merged and build a unique class which Demo1 and Demo2 are member for Demo

internal class Demo
public static void Demo1()
//do some operations

public static void Demo2()
//do some different operations

when youare using Entity Framework you saw how your DBContext will be separated two partial class.

Extension Methods
Extension methods uses "this" as keyword in its parameter and it should be declared in public static class
Extension method enables you to determine more method and add them to existing ones without recompiling, driving or even modifing original ones.

public static class Extension
public class string Lower (this string value) 

return value.ToLower();

When you need this method it is similar to call method: 

string value = "MAHSA";
value = value.Lower();

Tag: ,, , , , , ,

Rss Feed

Feedback: Feel free to leave any feedback on this article; it is a pleasure to see your comments about this code. If you have any questions, please do not hesitate to ask me here.
Your email address will not be published. All fields are Required

Pazooki | Sunday 10 2014 21:0
Very nice article, looking forward for your next one.
Mahsa Hassankashi | Monday 10 2014 15:30
Hi DEar @Pazooki Thank you for your comment
Jevgenijus | Tuesday 10 2014 22:59
Nice job, the way most articles should look like. Some sample links are broken...
Mahsa Hassankashi | Wednesday 10 2014 19:20
Hi Dear @Jevgenijus , Thank you for your comment and points, I checked broken links and edited them. There were two links for Collection and EF ModelFirst but if you downloaded first link as called "Data Access Sample File" you can see all of files that are related to this article.
Ananth.d | Friday 11 2014 19:1
very useful artical for me thanks.
Mahsa Hassankashi | Sunday 11 2014 2:46
Hi Dear @Ananth. You are most welcome. Thank you for your comment.
Manoj Verma | Thursday 11 2014 4:41
Hi Mahsa, It's great tutorial for beginners and thanks for your dedication to blog writing. I have one suggestion,if you like Can you divide article into parts like (Collection, Linq, Entity framework)? because reader can complete one topic at a time and implement easily instead of merging all the topics at a time. and thanks again for your charity work which i saw on your blog,its really great work.
Mahsa Hassankashi | Friday 11 2014 3:58
Hi Dear @Manoj Thank you so much for your comments and points. It is good idea to separate some parts and shrink its volume. I think it is more easier to read it. I will do it ASAP. I am so gratitude for your paying attention to this charity institution, you are so nice for that, God bless you. Best Regards.
RAFFI SHAIK | Monday 12 2014 1:41
Wow this is Very Very Nice and Understandable Thank u U Doing Good Job I Love you ...............
Jafar Ulla | Monday 1 2015 0:23
Masha Allah. Very nice work.
Inam Abbas | Tuesday 1 2015 3:8
it better if you allow to any one can post our article
Mahsa Hassankashi | Tuesday 1 2015 14:25
Hi Dear @RAFFI Thank you so much for your comment.
Mahsa Hassankashi | Tuesday 1 2015 14:28
Hi Dear @Jafar Thank you so much for your comment.
Mahsa Hassankashi | Tuesday 1 2015 14:31
Hi Dear @Inam Thank you so much for your comment. Your suggestion is so nice and I will consider it in near future. But for now if anyone has their own article I accept it warmly to put it with their name in my web site , you are welcome in web site gate. :)
sanjay | Thursday 1 2015 0:17
Very Nice Explanation...
Ali | Saturday 2 2015 0:56
Great Atricle, I'll prepare a video about how to write code first web application with high level performance and will link your article as reference. tnx
Imran KHan | Saturday 2 2015 0:28
I simply review your artical. very great explanation. Just a fan of you from now :)
José G. Ramírez | Sunday 2 2015 8:18
Brillante artículo, Mahsa Hassankashi. Me quito el sombrero. Gran esfuerzo que compartes. Sin ésta nutrida información, nuestros esfuerzos fuesen más débiles. Un saludo desde Venezuela.
Mahsa Hassankashi | Sunday 2 2015 9:56
Hello Dear @Sanjay Thank you so much for your comment
Mahsa Hassankashi | Sunday 2 2015 10:7
Dear @Ali you are most welcome to use content wherever and whenever you want. I am happy to hear that it is useful for you :)
Mahsa Hassankashi | Sunday 2 2015 10:10
Hi Dear @Imran you are most welcome to this site, It is my pleasure to have fan such you.
Mahsa Hassankashi | Sunday 2 2015 10:16
Hi Dear @Ramírez Thank you so much for your nice comment in your sweet language (Spanish). You are most welcome to this site.
naci | Monday 3 2015 12:41
Very nice article. masallah.
Mugunthan | Monday 4 2015 2:32
Nice Artical.You Have any video Artical in same
Ashok kamble | Thursday 4 2015 1:48
Great Explanation!!
Frederic VIAS | Tuesday 5 2015 23:34
Great article and a big job. Thank you for explaining all these concepts in one article.
Mahsa Hassankashi | Wednesday 5 2015 13:23
Thank you so much Dear @Naci for your comment. You are welcome to this site.
Mahsa Hassankashi | Wednesday 5 2015 13:30
Thank you so much Dear @Mugunthan for your comment. My next step in this tutorial field is to prepare video tutorial that I will share it from here.
Mahsa Hassankashi | Wednesday 5 2015 13:32
Thank you so much Dear @Ashok kamble for your comment. You are most welcome to this site.
Mahsa Hassankashi | Wednesday 5 2015 13:35
Thank you so much Dear @Frederic VIAS for your nice comment and idea about this article. You are most welcome to this site.
Anand Vemuri | Tuesday 5 2015 2:10
Hi Mahsa, Thank you so much for your patience to writing such a informative article, very well covered most of the topics with examples nice to read very helpful.
Mahsa Hassankashi | Friday 5 2015 15:36
Hello Dear @Anand Vemuri You are most welcome to this site. It is my pleasure to hear from you that it is helpful.
Rajesh Patil | Saturday 5 2015 7:44
This is exactly I was looking for. All collections at one place and explained in short and simple way. Its clear lot of my confusions and its good to compare and understand them with almost 0% confusion. Thanks lot for your hard work to bring this info together.
Luis Llamas | Thursday 6 2015 13:35
Nice work!
| Friday 8 2015 5:34
Very nice article
| Thursday 9 2015 9:55