Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / C#

ADO.NET Entity Framework as Data Access Layer

Rate me:
Please Sign up or sign in to vote.
4.19/5 (12 votes)
30 Oct 2009Public Domain2 min read 106.2K   4.3K   75   7
ADO.NET Entity Framework as Data Access Layer

Introduction

This article is targeted at beginner developers who want to learn how to use ADO.NET Entity Framework as Data Access Layer for their application. In this article, a simple CRUD operation is written in C# over the Entity Framework library. Unit Test Cases are also included so that code can be tested against some real time data.

Unzip the code application, execute the database script so that database schema gets created.

Elementary Knowledge of Lambda Expression is essential for understanding the search criteria.

ADO.Net Entity Framework

This is Microsoft's new framework that is used to generate the entity data model against the database. It reduces the code and time to create object based data application against existing database. Steps to generate the EDM.

  • In the solution, add a new project named DataAccessLayer.
  • Right Click on the Project and click on the Add --> New Item.

    Image 1

  • From the Add New Item dialog box, select ADO.NET Entity Data Model

    Image 2

  • Change the Name from Model1.edmx to TestModel.edmx. Click on the Add button
  • Entity Data Model Wizard will prompt. Select Generate from database and click on the next button.

    Image 3

  • Click on the New Connection.... button in dialog box.

    Image 4

  • From the connection property dialog box, we can select the server and database and enter user credentials to access database and test by clicking on the test connection button. Once done, click on the OK button.

    Image 5

  • From the next dialog box, select the tables as shown in the below picture and click on the finish button.

    Image 6

  • Now add a class file in the project and name it CustomerDbOperation.cs. Add 4 methods there:
    • SaveRecord
    • UpdateRecord
    • GetRecord
    • DeleteRecord

Using the Code

There are four methods in the application.

SaveRecord method takes Customer object as parameter and persists in the database and returns the CustomerId of the newly generated record in the database.

C#
public int SaveRecord(Customer record)
{
    using (testEntities = new TestEntities())
    {
        testEntities.AddToCustomer(record);
        testEntities.SaveChanges();
    }
    return record.CId;
} 

UpdateRecord updates the existing record in the database.

C#
public bool UpdateRecord(Customer record)
{
    EntityKey key;
    object originalItem;

      using(testEntities = new TestEntities())
      {
        key = testEntities.CreateEntityKey("Customer", record);

        if(testEntities.TryGetObjectByKey(key, out originalItem))
        {
            testEntities.ApplyPropertyChanges(key.EntitySetName, record);
        }

        testEntities.SaveChanges();

        return true;
    }
}

GetRecord prepares the object query and filters the customer records from the database.

C#
public List<customer> GetRecord(Customer record)
{
    testEntities = new TestEntities();
    IQueryable<customer> custQuery = testEntities.Customer.AsQueryable<customer>();
    if (record.CId > 0)
    {
        custQuery = custQuery.Where(c => c.CId == record.CId);
    }
    if (!string.IsNullOrEmpty(record.CFirstName))
    {
        custQuery = custQuery.Where(c => c.CFirstName.Contains(record.CFirstName));
    }
    if (!string.IsNullOrEmpty(record.CLastName))
    {
        custQuery = custQuery.Where(c => c.CLastName.Contains(record.CLastName));
    }
    if (!string.IsNullOrEmpty(record.CAddress))
    {
        custQuery = custQuery.Where(c => c.CLastName.Contains(record.CAddress));
    }
    return custQuery.ToList();
}

DeleteRecord method deletes the record from database.

C#
public bool DeleteRecord(Customer record)
{
    using (testEntities = new TestEntities())
    {
        var cust = testEntities.Customer.FirstOrDefault(c => c.CId == record.CId);
        testEntities.DeleteObject(cust);
        testEntities.SaveChanges();
        return true;
    }
}

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication


Written By
Architect
India India
Sarvesh Upadhyay is Technical Architect in Microsoft Technologies with 12 yrs of hands on experience on various domain like CRM, CMS, Inventory Management System, Telecome Billing, E-Commerce application, Retail etc.
He has indepth knowledge on Design Patterns, Asp.Net MVC, MVP , C#, JavaScript, Knockout, MS-SQL Server,Web Services,Web API, MSMQ, Saleslogix CRM, etc.

Comments and Discussions

 
QuestionHow to reduce process speed of GetRecord in Entity Framework? Pin
m_Shadman20-Aug-13 1:37
m_Shadman20-Aug-13 1:37 
QuestionProblem in creating new TestEntites() Pin
Member 975660530-Jun-13 23:01
Member 975660530-Jun-13 23:01 
GeneralMy vote of 3 Pin
Qadri Jillani19-Jun-13 21:39
Qadri Jillani19-Jun-13 21:39 
QuestionConstructors and classes Pin
Member 967354721-Jan-13 12:40
Member 967354721-Jan-13 12:40 
Generalok article Pin
Donsw10-Jun-10 8:22
Donsw10-Jun-10 8:22 
GeneralBlocks of code should be wrapped in &lt;pre&gt; tags like this: Pin
Talking Dotnet29-Oct-09 18:16
Talking Dotnet29-Oct-09 18:16 
GeneralRe: Blocks of code should be wrapped in &lt;pre&gt; tags like this: Pin
sarvesh.upadhyay30-Oct-09 0:14
professionalsarvesh.upadhyay30-Oct-09 0:14 
Thanks for pointing out this. Smile | :)

Sarvesh Upadhyay
Senior Software Engineer
Birlasoft India Ltd.
Microsoft Certified Professional Developer in Dotnet 2.0 Enterprise Application

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.