Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » ADO.NET & Database » Getting started with ADO.NET Entity Framework in .NET 3.5

Getting started with ADO.NET Entity Framework in .NET 3.5

This article contains a very simple ADO.NET Entity Framework application to display and add the data to the database using ADO Entity Framework.

Page Views : 59742
Downloads : 1219
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Payroll.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


ADO.NET Entity Framework is an object-relationship management (ORM) tool like Hibernate in java or N Hibernate for .net. ADO.NET Entity Framework is included with .NET Framework 3.5 Service Pack 1 and Visual Studio 2008 Service Pack 1. Please make sure you have and Visual Studio 2008 Service Pack 1 installed in your system. For more information about ADO.NET Entity Framework you can refer to Microsoft site.

One practical is worth more than a thousand words. So let us start with creating a very simple example.

Step 1: Create a database table.

Create a database in SQL Server 2005 and name it as Payroll.

On the payroll database create an Employee table as follows.

USE [Payroll]

GO

 

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE TABLE [dbo].[Employee](

          [EmployeeID] [int] IDENTITY(1,1) NOT NULL,

          [Name] [nvarchar](50) NOT NULL,

          [Title] [nvarchar](50) NOT NULL,

          [BirthDate] [datetime] NOT NULL,

          [MaritalStatus] [nchar](1) NOT NULL,

          [Gender] [nchar](1) NOT NULL,

          [HireDate] [datetime] NOT NULL,

 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED

(

          [EmployeeID] ASC

)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

) ON [PRIMARY]

Step 2: Data Layer

In the visual studio 2008 Make a new Blank solution and name it as Payroll. In the solution add a new class library project. Name it as Payroll.Entities as shown in following image.

 

Remove the class1.cs from project. Add a new item to project a select. ADO.NET Entity data Model.

 

Rename it as Payroll.edmx. Click on add. Select generate from the database and click on next choose database connection and the given textbox for connection string rename it with PayrollDAO

 

From the next screen select the employee table and click on finish. Compile the project. Now data layer is ready for you.

Step 3: Business/Service Layer

In the solution Payroll add a new class library project. Name it as Payroll.Service. Rename the class1.cs as EmployeeService.cs. Make the reference to System.Data.Entity. and also add the refrence to Payroll.Entities project we have created. Now add two methods GetEmployee and AddEmployee. Your class should look like this

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Payroll.Entities;

using System.Data.Objects;

using System.Data.Objects.DataClasses;

 

namespace Payroll.Service

{

    public class EmployeeService

    {

        public List<Employee> GetEmployee()

        {

            PayrollDAO payrollDAO = new PayrollDAO();

            ObjectQuery<Employee> employeeQuery = payrollDAO.Employee;

            return employeeQuery.ToList();

        }

        public string AddEmpoyee(Payroll.Entities.Employee e1)

        {

            PayrollDAO payrollDAO = new PayrollDAO();

            payrollDAO.AddToEmployee(e1);

            payrollDAO.SaveChanges();

            return "SUCCESS";

        }

    }

}

Compile the project. Service layer is ready for you.

Step 4: Presentation Layer

Add a new web site with name "WebApp" to the payroll solution and set it as startup project. In the default.aspx add a gridview and button as shown in following figure

 

Set button text to Add Employee. Make the reference to System.Data.Entity and also add the refrence to Payroll.Service project we have created in step 3.

Add the code on page load and buttion1_click, Default.aspx.cs should look like this

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using Payroll.Service;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        EmployeeService  es= new EmployeeService();

        GridView1.DataSource = es.GetEmployee();

        GridView1.DataBind();

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        EmployeeService es = new EmployeeService();

        DateTime dt = new DateTime(2008, 12, 12);

 Payroll.Entities.Employee e1 =     Payroll.Entities.Employee.CreateEmployee(0, "Anand", "Thakur", dt, "M", "M", dt);

        es.AddEmpoyee(e1);

    }

}

Copy the connectionStrings from App.config of Data Layer(Payroll.Entities) project and paste in web.config of web application

<connectionStrings>
          <add name="PayrollDAO" connectionString="metadata=res://*/Payroll.csdl|res://*/Payroll.ssdl|res://*/Payroll.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=ATHAKUR;Initial Catalog=Payroll;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>

Now build and run the web application.

 

Click on add employee, new employee should be added to database.

Conclusion:

This is a very basic example with single table. In the next part, I will try to include more tables with CRUD operations.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Anand Thakur

 

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Great example by Mahesh On October 1, 2008
Thanks Anand. I haven't use ADO.NET entity framework yet but looks pretty cool. I would like to see samples for about edit and delete employees. Cheers!
Reply | Email | Modify 
FX Cop by ts_az On October 1, 2008
You should run FX-Cop on your samples. You have some issues.
Reply | Email | Modify 
Re: FX Cop by Anand On October 3, 2008
Thanks for your suggestion, This a very simple example for understanding. I don't think we needs to run FxCop for this. By the way what problem are you facing
Reply | Email | Modify 
Good Example to understand ADO.NET Entity Framework by Raghavendra On October 3, 2008

Hi Anand, This is good article and explains basic understanding of the ADO.NET Entity Framework, I am waiting to see advanced concepts of the same.

GOOD WORK and Thanks

Raghavendra, Software Developer,London,UnitedKingdom

Reply | Email | Modify 
Examples for Windows Forms DataGridView? by eluim On October 7, 2008
hello, as a newbie in c# i would appreciate application examples with databinding to datagridview with CRUD operations between N:M and 1:M relations. Beside that thank you very much for your time you invest in writing these articles :)
Reply | Email | Modify 
Re: Examples for Windows Forms DataGridView? by Arun On November 19, 2008

Artical explained with simple example....very nice...thanks

Reply | Email | Modify 
using Ado.net Entity Framework with stored procedure by Naresh On December 3, 2008
It's a very great article but it doesn't inform how to use stored procedure with Entity framework . I have a stored procedure that returns columns from two table, i want to bind the result set of this sp to Gridview. How can i use Ado.Net Entity model to achieve this. Any help would be appreciated. Regards, Naresh Jakher
Reply | Email | Modify 
Good Presentation by Ajith On December 5, 2008
Hi Anand, The way you presented ADO.Net Entitiy Frame is excellent. Any beginner to this technology can easily understand your example and it will give him/her confident for going forward. Thanks -Ajith
Reply | Email | Modify 
Best Tutorial I've found! by Nannette On December 5, 2008

This is the best tutorial I've found! And I was able to easily convert it to VB and use my own tables and just follow along with your directions and it worked the first time! This is also great for learning how to create a 3 layer project and adding the references, etc. Great job! I've been looking for this for a long time!

Nannette

Reply | Email | Modify 
Sql Server Express 2008 by Lewis On May 29, 2009
Hi Anand,

Is Sql Server Express 2008 an OK replacement for Sql Server 2005 in this usage?
Reply | Email | Modify 
Thanks alot by Debasish On January 3, 2010
Thanks Alot!!!
Mr Anand Thakur, The article is very useful for begineers like me.
The way of representation is very simple to understand the basic concept of EDM.

But in the "Entity Dta Model Wizard" the databese that i have created is not coming.
What might be the reason. Plz let me know.
Reply | Email | Modify 
Good Example..! by vilas On April 22, 2010
Hi Anand, Very nice example, its very easy to understand EF..
And one more point, the photo which u uploaded is very cute one... is this ur child..?

Regards,
Vilas
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.