Click here to Skip to main content
15,867,756 members
Articles / Web Development / ASP.NET

Simple Sample with Entity Framework

Rate me:
Please Sign up or sign in to vote.
4.33/5 (32 votes)
9 Jul 2009CPOL3 min read 353.6K   20.3K   63   20
Simple sample with entity framework in 3 layers with ASP.NET

Introduction

This sample shows how you can use the entity framework in an application ASP.NET with an architecture in layers. This is useful for applications that are pretty small and fast. The code uses select, update, create and delete functions. You can use this example with stored procedures or without this. This sample is aimed at newcomers to EF.

This is a small idea that occurred to me to implement the concepts of Entity Framework in ASP.NET, but I'm honest I stumbled across a lot of blocks while making this exercise. The first context is complex and that creates some objects in memory, on the other hand I had to send objects to be processed. There was no need for stored entity framework to be a key, otherwise errors would be raised.

Database

First view the structure of the database. This example uses two tables, i.e., Customers and Category. Customers have a relation with Category.

imgbdsolution.JPG

Project

The project has a structure in three layers. The layer for business that contains the project entities, the project components, the layer of data and the layer of presentation.

imglayer.JPG

The layer of business contains two projects that are Solution.Bussines.Entities. This contains the same structure of the tables and is mapped with the structure of the database.

The Model has the same structure of database which uses ADO.NET Entity Data Model.

imgmodelsolution.JPG

The table customer has a relation with stored procedures.

imgrelationcustomer.JPG

It is important that you see the relation for delCustomer, you only need Id for delete but the entity framework is required for the table referenced.

The next class Customers extends the model generated with ADO.NET Entity Data Model which uses CategoryReference for loading Category of Customer in the line:

C#
this.CategoryReference.Load();

This form easily obtains a class referenced in another class and can also be used for showing in a grid.

C#
public partial class Customers
{
public const string EntitySetName = "Customers";

[Browsable(false)]
public string CategoryName
{
get
{
string res = "";
if (this.Category != null)
{ 
res = this.Category.Name; 
}
else if (this.CategoryReference != null)
{
this.CategoryReference.Load();
if (this.Category != null)
{ 
res = this.Category.Name; 
}
}
return res;
}
set
{
this.CategoryReference.EntityKey =
new EntityKey("CustomersEntities.Category", "CategoryId", value);
}
}

In the next fragment of code was extended the class entities or best call context for that has a singleton pattern and solution to the problem of creating many instances that do not close completely when you use using or dispose.

C#
public static CustomersEntities Context
{
get
{
string objectContextKey = HttpContext.Current.GetHashCode().ToString("x");
if (!HttpContext.Current.Items.Contains(objectContextKey))
{
HttpContext.Current.Items.Add(objectContextKey, new CustomersEntities());
}
return HttpContext.Current.Items[objectContextKey] as CustomersEntities;
}
}

Business Layer

The Solution.Bussines.Components layer manages the logic of business and joins the layer of data with the layer of entities.

This layer is composed by the class CustomersComponent.cs which calls the layer of data. Here you can add more logic code for your business.

C#
/// <summary>
/// Submit an Customers.
/// </summary>
/// <param name="Customers">An Customers object.</param>
public Customers CreateCustomer(Customers customers)
{
Console.WriteLine("Submitting... "); 
try
{
customers = CreateCustomers(customers); 
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw ex;
}

Console.WriteLine("New CustomersID = " + customers.Id.ToString());
return customers;
}

/// <summary>
/// Creates a new Customers record in the database.
/// </summary>
/// <param name="customers">An Customers object.</param>
private Customers CreateCustomers(Customers customers)
{
// Business logic.
Console.WriteLine(customers.ToString());

// Persist data.
CustomersDAC dac = new CustomersDAC();
return dac.Create(customers);
}

List a customer by name, this method calls the layer of data access.

C#
/// <summary>
/// return a list of customers by name
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public List<Customers> ListCustomersByName(string name)
{
// Retrieve data.
CustomersDAC dac = new CustomersDAC();
return dac.SelectByName(name);
}

Data Layer

The data layer contains the logic for accessing the database.

Insert a new record in the database. This method uses the customer created previously for adding to context and saving the changes in the database.

C#
/// <summary>
/// Inserts an Customers row.
/// </summary>
/// <param name="Customers">An Customers object.</param>
public Customers Create(Customers customers)
{
CustomersEntities ctx = CustomersEntities.Context;//)
try
{
ctx.AddToCustomers(customers); 
ctx.SaveChanges();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
throw ex;
} 
return customers;
}

Update a record in the database. This method does not add the object to context because the previous one was obtained.

C#
/// <summary>
/// Updates an Customers row.
/// </summary>
/// <param name="Customers">A Customers object.</param>
public void Update(Customers Customers)
{
    CustomersEntities ctx = CustomersEntities.Context;//)

    try
    {
        ctx.SaveChanges(); 
    }
    catch (Exception ex){

    Debug.WriteLine(ex.Message);
    throw ex;
    }
}

The context contains the tables as properties so that you can access this and obtain the list of generic classes.

The next method selects the records of the customers table.

C#
/// <summary>
/// Returns a set of Customers that belongs to an employee
/// </summary>
/// <returns>A List of Customers.</returns>
public List<Customers> Select()
{
    List<Customers> resultsList = null;
    CustomersEntities ctx = CustomersEntities.Context;//)
    resultsList = ctx.Customers.ToList();
    return resultsList;
} 

The next method gets a record of the table customer by id. This uses the expression lambda for filter by Id. With the method First, you will surely get one record. After getting customer record, load the table referenced.

C#
public Customers getCustomer(int Id)
{
    Customers custre = null;
    CustomersEntities ctx = CustomersEntities.Context;
    {
        custre = ctx.Customers.First(e => e.Id == Id);
    }            
    custre.CategoryReference.Load();
    return custre;
}

The next method Delete records the table customer, first gets the record and later calls the method DeleteObject for deleting the record temporarily. Finally it calls Save changes that ensures save in the database.

C#
public void Delete(int Id)
{
    CustomersEntities ctx = CustomersEntities.Context;
    Customers cust = ctx.Customers.First(c => c.Id == Id);
    ctx.DeleteObject(cust);
    ctx.SaveChanges();
}

Presentation Layer

In the presentation layer built in ASP.NET, we have the form for update or add records, the principal method sends to the layer components the action for that to execute in the database. This first fills the object customer with the form information and the next calls Update or Add.

For updating a record, first get a record of the context.

C#
protected void btnEnviar_Click(object sender, EventArgs e)
{
CustomersComponent custc = new CustomersComponent();
Customers cust = null; 
// if id customer for edit
if (Id > 0)
{
    cust = custc.getCustomer(Id);
    cust.Name = txtName.Text;
    Category category = custc.GetCategory(
    int.Parse(ddlCategories.SelectedValue));
    cust.Category = category;
    custc.UpdateCustomer(cust);
}
else
{ 
    // agregar 
    cust = new Customers();
    cust.Name = txtName.Text;
    Category category = custc.GetCategory(
    int.Parse(ddlCategories.SelectedValue));
    cust.Category = category;
    custc.CreateCustomer(cust);
}
Response.Redirect("Default.aspx");
}

The next method loads a customer in a form:

C#
private void LoadCustomer()
{
    CustomersComponent custc = new CustomersComponent();
    Customers cust = custc.getCustomer(Id);
    txtName.Text = cust.Name;
    ddlCategories.SelectedValue = cust.Category.Id.ToString();
}

Please comment and vote for this article for it to improve the next time.

History

  • 9th July, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Telecomunicaciones S.A. Esp
Colombia Colombia
Steve X. Cardenas are Developer of software, web sites. is creator of any web sites for magazines, also developer for other industries.
Systems engineer, Specialist in engineering software, certified net and development sharepoint.

Comments and Discussions

 
QuestionSeems that download link is broken Pin
Member 111361457-Oct-14 9:32
Member 111361457-Oct-14 9:32 
GeneralExcellent Pin
Musakkhir15-Mar-14 23:41
professionalMusakkhir15-Mar-14 23:41 
GeneralExcellent Article Pin
Rich.Edwards17-Jun-13 23:27
Rich.Edwards17-Jun-13 23:27 
GeneralMy vote of 4 Pin
waelali831-May-13 7:35
waelali831-May-13 7:35 
GeneralMy vote of 4 Pin
pothiq5-Sep-12 8:28
pothiq5-Sep-12 8:28 
QuestionA bit complicated Pin
ybonda4-Aug-12 0:19
ybonda4-Aug-12 0:19 
GeneralThanks Pin
Shovra21-Apr-12 6:41
Shovra21-Apr-12 6:41 
GeneralMy vote of 3 Pin
tarik0774-Apr-12 22:42
tarik0774-Apr-12 22:42 
GeneralMy vote of 2 Pin
fish5525-Apr-11 3:53
fish5525-Apr-11 3:53 
GeneralMy vote of 3 Pin
vsr.krishnamraju10-Feb-11 22:09
vsr.krishnamraju10-Feb-11 22:09 
GeneralMy vote of 5 Pin
Arlen Navasartian9-Feb-11 5:54
Arlen Navasartian9-Feb-11 5:54 
GeneralPassing CategoryId in delCustomers Pin
Arlen Navasartian9-Feb-11 5:40
Arlen Navasartian9-Feb-11 5:40 
Generaluse english only in application Pin
sunil parihar7-Dec-10 19:15
sunil parihar7-Dec-10 19:15 
GeneralStatic context Pin
jportelas14-Sep-10 10:37
jportelas14-Sep-10 10:37 
GeneralRe: Static context Pin
Arash Javadi29-Nov-11 21:34
Arash Javadi29-Nov-11 21:34 
Generalgood article Pin
Donsw3-Oct-09 18:34
Donsw3-Oct-09 18:34 
General¡Buen artículo! Pin
CDFaux10-Jul-09 2:24
CDFaux10-Jul-09 2:24 
GeneralRe: ¡Buen artículo! Pin
Mi.Chal.10-Jul-09 6:05
Mi.Chal.10-Jul-09 6:05 
GeneralRe: ¡Buen artículo! Pin
JoanGilabert13-Jul-09 21:12
JoanGilabert13-Jul-09 21:12 

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.