How to create a simple data access layer using Repository Pattern with Entity Framework

This is a step by step guide to add Entity Framework to our application and create Repository Pattern to simplify data access. This tutorial written based on the database created earlier.

1. Create data model

First, we will create the data model of our database. Right click on our project > Add New Item > ADO.NET Entity Data Model > Generate from Database > Set Entities Connection to DatabaseContext.

Create Repository Pattern DAL using Entity Framework | SamuraiListing Example

Create Repository Pattern DAL using Entity Framework | SamuraiListing Example

Make sure you choose all the Tables as showed below.

Create Repository Pattern DAL using Entity Framework | SamuraiListing Example

You should be able to see the model diagram similar to the below if it’s done well.

Create Repository Pattern DAL using Entity Framework | SamuraiListing Example

2. Create an Interface for our Repository. Add New Item > Interface > Name it IRepository.cs

Create Repository Pattern DAL using Entity Framework | SamuraiListing Example

Paste these codes into IRepository.cs file. These codes create a generic interface contract that all our repository adhere, it’s like a contract that we provide to other developers on what our repository offer.

using System.Linq;

namespace SamuraiListing.Data
{
    public interface IRepository<T> where T : class
    {
        IQueryable GetAll();
        T GetById(int id);
        void Add(T entity);
        void Update(T entity);
        void Delete(T entity);
        void Delete(int id);
    }
}

3. Create our Repository that implements the interface that we have just declared. Add New Item > Class > Name it Repository.cs

Create Repository Pattern DAL using Entity Framework | SamuraiListing Example

using System;
using System.Data;
using System.Data.Entity;
using System.Linq;

namespace SamuraiListing.Data
{
    public class Repository<T> : IRepository<T> where T : class
    {
        protected DatabaseContext DbContext { get; set; }
        protected DbSet DbSet { get; set; }

        public Repository(DatabaseContext dbContext)
        {
            if (dbContext == null) throw new NullReferenceException("dbContext");
            DbContext = dbContext;
            DbSet = dbContext.Set();
        }

        #region Implementation of IRepository<T>

        public IQueryable GetAll()
        {
            return DbSet;
        }

        public T GetById(int id)
        {
            return DbSet.Find(id);
        }

        public void Add(T entity)
        {
            DbSet.Add(entity);
        }

        public void Update(T entity)
        {
            var entry = DbContext.Entry(entity);
            DbSet.Attach(entity);
            entry.State = EntityState.Modified;
        }

        public void Delete(T entity)
        {
            var entry = DbContext.Entry(entity);
            DbSet.Attach(entity);
            entry.State = EntityState.Deleted;
        }

        public void Delete(int id)
        {
            var entity = GetById(id);
            if (entity == null) return;
            Delete(entity);
        }

        #endregion
    }
}

4. With this, we created our Repository for all the classes from our database.

We can now use the code below to perform CRUD to our database. We are not done yet, please refer to my next post about Unit of Work implementation to complete our Database access layer. Thanks.

// Create database context with the app.config connection string.
var dbContext = new DatabaseContext();
// Create repository for Company class.
var companyRepository = new Repository(dbContext);

// Get the first company in our database records
var firstCompany = companyRepository.GetAll().First();

var newCompany = new Company { Name = "BizVise.com", Telephone = "012-9042869", Email = "support@bizvise.com", GPS = "2.251189,102.277578" };
companyRepository.Add(newCompany);
// I cheated here a bit because i didn't implement the .Save() method to save it to database.
// Refer to my next post on the Unit of Work implementation for the complete implementation.
//companyRepository.Save();
Advertisements

3 comments

  1. Pingback: How to create a simple data access layer Unit of Work pattern with Entity Framework | BizVise - Melaka Software Development

  2. Pingback: Simple KendoUI Example – SamuraiListing | BizVise - Melaka Software Development


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s