Click here to Skip to main content
13,596,080 members
Click here to Skip to main content
Add your own
alternative version


68 bookmarked
Posted 13 Mar 2013
Licenced CPOL

Repository Pattern with Entity Framework using EntityTypeConfiguration

, 20 Mar 2013
Rate this:
Please Sign up or sign in to vote.
Repository Pattern with Entity Framework using EntityTypeConfiguration.


I was looking for Repository Pattern with Entity Framework Code First with EntityTypeConfiguration. But unable to find such integrated sample. Here I am touching only the basic. It's my first article.


I am taking plain two objects Category and Product to make this article simple.

Using EntityTypeConfiguration for making different layer to interact with Database and field validation.

Following is the Solution tree. 

**Note: need to add Entity Frame work reference in the EfRepPatTest.Data  project.

Development Tools

VS 2010

Entity Framework Library

Using the code 

First of all we shall create three Projects in the solution, of them two's are class library and the other one is console project for Implementation.
Solution Name: EfRepositoryPatterTest
Class Library Name: EfRepPatTest.Entity
Console Application: EfRepPatTest.Implementation  

In the EfRepPatTest.Entity project we shall create the following class:


public class BaseEntity<T>
    public T Id { get; set; }

IRepository.cs [Interface]

That contains action of

public interface IRepository<TEntity> where TEntity:class 
    IQueryable<TEntity> GetAll();
    TEntity GetById(object id);
    void Insert(TEntity entity);
    void Update(TEntity entity);
    void Delete(TEntity entity);


It will inherit BaseEntity class for getting the Id property and assigning Id field as integer.

public class Category:BaseEntity<int>
    public virtual string Name { get; set; }

    public List<Product> Products { get; set; }


Same as category class.

public class Product:BaseEntity<long>
    public virtual int CategoryId { get; set; }
    public virtual Category Category { get; set; }
    public virtual string Name { get; set; }
    public virtual int MinimumStockLevel { get; set; }


EfRepPatTest.Data project hold the following classes or interfaces.

Add reference of EntityFramework and EfRepPatTest.Entity in this project.

First of all create an interface that driven DbContext class means DataContext class will consume.


public interface IDbContext

    IDbSet<TEntity> Set<TEntity>() where TEntity:class;
    int SaveChanges();
    void Dispose();

Here IDbSet interface belongs to System.Data.Entity namespace. Create a class name DataContext that will inherit DbContext and consume IDbContext.

DataContext.cs [Partial]

public class DataContext: DbContext,IDbContext
    public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
        return base.Set<TEntity>();

Before discussing the DataContext class’s method we need another two class that will map Entity with EntityTypeConfiguration and holds data validation logic of Database table.

Create folder name Mapping and place the CategoryMap and ProductMap class in it. [optional]


public class CategoryMap:EntityTypeConfiguration<Category>
    public CategoryMap()
        HasKey(c => c.Id).Property(c => c.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(c => c.Name).IsRequired().HasMaxLength(50);


public class ProductMap:EntityTypeConfiguration<Product>
    public ProductMap()
        HasKey(p => p.Id).Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        //CategoryId as foreign key
        HasRequired(p => p.Category)
            .HasForeignKey(p => p.CategoryId);
        Property(p => p.Name).IsRequired().HasMaxLength(100);
        Property(p => p.MinimumStockLevel);

The above part will help us avoiding directly use of Entities[Product and Category] as database table, instead it will cover db table logic, validation.

Now add "OnModelCreating" method in DataContext class for attaching the Entity as part of model.The following code snippet will demonstrates how to configure EntityTypeConfiguration driven class [ProductMap, CategoryMap] with ModelBuilder manually.


         modelBuilder.Configurations.Add(new CategoryMap());

         modelBuilder.Configurations.Add(new ProductMap());



Here problem is all of the classes need to be configure manually. That’s why I would like to avoid it. The following codes will help us to do it automatically.

DataContext.cs [Full]

public class DataContext: DbContext,IDbContext
    public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
        return base.Set<TEntity>();

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
        var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
        .Where(type => !String.IsNullOrEmpty(type.Namespace))
        .Where(type => type.BaseType != null && type.BaseType.IsGenericType && 
           type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
        foreach (var type in typesToRegister)
            dynamic configurationInstance = Activator.CreateInstance(type);



we haven’t implement the IRepository interface yet, through RepositoryService class we will implement it. 


public class RepositoryService<TEntity>:IRepository<TEntity> where TEntity:class 
    private IDbContext Context;

    private IDbSet<TEntity>  Entities
        get { return this.Context.Set<TEntity>(); }

    public RepositoryService(IDbContext context)
        this.Context = context;


    public IQueryable<TEntity> GetAll()
        return Entities.AsQueryable();

    public TEntity GetById(object id)
        return Entities.Find(id);

    public void Insert(TEntity entity)

    public void Update(TEntity entity)
        if (entity == null)
            throw new ArgumentNullException("entity");


    public void Delete(TEntity entity)

    public void Dispose()
    protected virtual void Dispose(bool disposing)
        if (disposing)
            if (this.Context != null)
                this.Context = null;

The "private IDbSet<TEntity>  Entities" property will returns DbSet instance for access to einties of the given type in the context.

Now need a class for initializing the Database. Add a class named DataBaseInitializer.


public class DataBaseInitializer : IDatabaseInitializer<DataContext>
    public void InitializeDatabase(DataContext context)

Implementing the application through  EfRepPatTest.Implementation console project:

The Program.cs class looks like the following:  

class Program
    static void Main(string[] args)
        var context = new DataContext();
        var dataBaseInitializer = new DataBaseInitializer();

        var categoryRepository = new RepositoryService<Category>(context);

        //Adding category in the category entity
        var category = new Category()
            Name = "Baverage"
        var products = new List<Product>();

        //Adding product in the product entity
        var product = new Product()
                Name = "Soft Drink A",
                MinimumStockLevel = 50

        product = new Product()
            Name = "Soft Drink B",
            MinimumStockLevel = 30

        category.Products = products;

        //Insert category and save changes

        /////////////////For the next project we shall add Dependency Injection////////
        ////////////////But now we have add a Service layer for test manually//////////
        IProductService productRepository = new ProductService();

        Console.WriteLine("Product List:");
        foreach (var product1 in productRepository.GetAll())
            Console.WriteLine(string.Format("Product Name : {0}",product1.Name));
            if (product1.Id == 9)

                product1.Name = "Soft Drink AAA";
        Console.WriteLine("Press any key to exit");

Here we have added "EfRepPatTest.Service" project to test the service. It will help us in the next article.

Connection string in App.config [highlighted portion]:

<?xml version="1.0" encoding="utf-8"?>
    <!-- For more information
on Entity Framework configuration, visit -->
    <section name="entityFramework" 

EntityFramework, Version=, Culture=neutral,

             requirePermission="false" />
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory,
EntityFramework" />

      <add name="DataContext" 


Source=YourSERVER;Initial Catalog=EfDBExistRepository;Integrated

As name of connection string [name="DataContext"] same as DataContext.cs class so it will work automatically. 

That's may help.

Next Article


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


About the Author

Software Developer (Senior)
Bangladesh Bangladesh
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralMy vote of 2 Pin
evgeniy.gryaznov5-Oct-13 18:53
memberevgeniy.gryaznov5-Oct-13 18:53 
QuestionHow to modify a database first? Pin
yourber29-Sep-13 15:11
memberyourber29-Sep-13 15:11 
GeneralMy vote of 2 Pin
AlluvialDeposit7-Jun-13 0:36
professionalAlluvialDeposit7-Jun-13 0:36 
Questionthanks Pin
noor rahman3-Jun-13 19:55
membernoor rahman3-Jun-13 19:55 
QuestionWork with WCF Pin
Yasithl8-May-13 3:25
memberYasithl8-May-13 3:25 
AnswerRe: Work with WCF Pin
MdAsifBd17-May-13 20:14
memberMdAsifBd17-May-13 20:14 
GeneralRe: Work with WCF Pin
Yasithl20-May-13 0:53
memberYasithl20-May-13 0:53 
SuggestionIDisposable Pin
Member 15540717-May-13 7:25
memberMember 15540717-May-13 7:25 
GeneralRe: IDisposable Pin
MdAsifBd7-Jun-13 9:08
memberMdAsifBd7-Jun-13 9:08 
QuestionMy vote of 2 Pin
Michael J. Eber26-Mar-13 6:36
memberMichael J. Eber26-Mar-13 6:36 
GeneralMy vote of 4 Pin
fredatcodeproject20-Mar-13 6:22
memberfredatcodeproject20-Mar-13 6:22 
GeneralRe: My vote of 4 Pin
MdAsifBd20-Mar-13 6:28
memberMdAsifBd20-Mar-13 6:28 
GeneralMy vote of 5 Pin
yanborowski20-Mar-13 3:55
memberyanborowski20-Mar-13 3:55 
GeneralMy vote of 2 Pin
tecgoblin18-Mar-13 23:54
membertecgoblin18-Mar-13 23:54 
GeneralRe: My vote of 2 Pin
phani krishna reddy v3-Dec-14 12:33
memberphani krishna reddy v3-Dec-14 12:33 
GeneralMy vote of 3 Pin
ZeroDotNet14-Mar-13 10:58
memberZeroDotNet14-Mar-13 10:58 
GeneralRe: My vote of 3 Pin
J. Wijaya14-Mar-13 17:43
memberJ. Wijaya14-Mar-13 17:43 
AnswerRe: My vote of 3 Pin
M Asif15-Mar-13 0:31
memberM Asif15-Mar-13 0:31 
GeneralMy vote of 5 Pin
A_Haider14-Mar-13 4:45
memberA_Haider14-Mar-13 4:45 
GeneralRe: My vote of 5 Pin
M Asif14-Mar-13 4:50
memberM Asif14-Mar-13 4:50 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04 | 2.8.180621.3 | Last Updated 20 Mar 2013
Article Copyright 2013 by MdAsifBd
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid