Click here to Skip to main content
Click here to Skip to main content

ADO.NET Entity Framework as Data Access Layer

By , 30 Oct 2009
Rate this:
Please Sign up or sign in to vote.

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.

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

  • 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.

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

  • 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.

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

  • 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.

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.

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.

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.

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

About the Author

sarvesh.upadhyay
Technical Lead
India India
Sarvesh Upadhyay is Technical Lead in Microsoft Technologies with 10 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

 
GeneralBlocks of code should be wrapped in &lt;pre&gt; tags like this: PinmemberVirendra Dugar29-Oct-09 18:16 
GeneralRe: Blocks of code should be wrapped in &lt;pre&gt; tags like this: Pinmembersarvesh.upadhyay30-Oct-09 0:14 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140415.2 | Last Updated 30 Oct 2009
Article Copyright 2009 by sarvesh.upadhyay
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid