Click here to Skip to main content
Licence Public Domain
First Posted 29 Oct 2009
Views 27,168
Downloads 1,031
Bookmarked 56 times

ADO.NET Entity Framework as Data Access Layer

By | 30 Oct 2009 | Article
ADO.NET Entity Framework as Data Access Layer
 
Part of The SQL Zone sponsored by
See Also

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

Web Developer

India India

Member

Sarvesh Upadhyay is Software developer on various domain like CRM, CMS, Inventory Management System, Telecome Billing, E-Commerce application etc. He has worked on Asp.Net, C#,Javascript, MS-SQL Server,Web Services,.Net Remoting, MSMQ,COM Programming in VB 6.0. He has worked on Saleslogix CRM. Currently he is working in Birlasoft India Ltd. as Senior Software Engineer.
He has done B.Sc.(Hons) from Calcutta University and MCPD in dotnet 2.0 Enterprise Application Developer.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Generalok article PinmemberDonsw8:22 10 Jun '10  
GeneralBlocks of code should be wrapped in <pre> tags like this: PinmemberVirendra Dugar18:16 29 Oct '09  
GeneralRe: Blocks of code should be wrapped in <pre> tags like this: Pinmembersarvesh.upadhyay0:14 30 Oct '09  

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.

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