Entity Framework 4 POCO, Repository and Specification Pattern [Upgraded to EF 4.1]

I am excited to announce that the framework has been upgraded to the new version to follow up with the final release of Microsoft ADO.NET Entity Framework 4.1 yesterday. The upgrade includes some changes from Entity Framework API itself and also incorporates bug fixed as well many great suggestion/comments for improvement from the readers. You can download the latest version of the framework (1.4 at this writing) at http://code.google.com/p/ef4prs/downloads/list and play around with it. Note that to be able to compile the code, you first need to download and install EF 4.1 using standalone installer or by adding nuget package to your project.

If you are new to this framework and the design idea behind it, take some time to read these posts first:

Happy coding!

Posted on April 13, 2011, in Entity Framework and tagged , , , , . Bookmark the permalink. 193 Comments.

  1. Good job, aHuy! It is really quick upgrade after EF CF 4.1 released yesterday.

  2. That’s just great news. I use your project literally as a base for all of my projects’ DALs.
    Geart job, and thanks for sharing it.

  3. You’re fast!

    I’ve been following your articles about EF and several patterns and using much of the knowhow on a new project I’m building from scratch.

    I have one question about using this sample with POCO generated from an EDMX using T4 template. What is the best approach that can be elegant and flexible at the same time?

    • My understanding is that you’re using database first development via generating EDMX that contains POCOs object. If so, you can pass in the generated data context to the repository. There is a test code that demonstrates how to do that at Infrastructure.Tests\Data\Lab\UseMyDbContext.cs. Yes, the test use DbContext but it I hope it gives you the idea how to do database first development with this framework.

      • Thank you for the tip. Actually it was easy, with your help, just as simple as to

        // My data context generated from T4 templates
        private SPSDataEntities1 context;
        // A sample test
        public void Init()
        context = new SPSDataEntities1();

        // Passing my context to the repository
        customerRepository = new CustomerRepository(context);
        repository = new GenericRepository();

        public void FindByUsername_Success()
        var c = customerRepository.FindByUsername(“mimolhos”);


        It works.

      • I’m trying a database-first implementation as well. We have an existing system, and I’d rather not have to map everything by hand. I still want to use your framework because it’s a great IRepository implementation. Do you have a recommended procedure for starting out with a completed .edmx model?

        Is it possible to convert an ObjectContext to a DbContext so that it can be passed in to the GenericRepository constructor?

        The way I see it, here’s what would happen in a perfect world:
        1) .edmx file is generated from reflecting on the database (this part is easy!)
        2) A repository class is created that implements IRepository. This would be in 2 parts; an interface, and a concrete class. Let’s call them IMyRepo and MyRepo.
        3) Rather than mapping all the POCOs manually, the mappings for MyRepo would be generated from the .edmx transformation.
        4) (Just a wish list now) Each of the Entity classes created from the .edmx generation would have its own interface that it implements. Now, instead of MyRepo.GetAll() we could use MyRepo.GetAll(). That lets the code be flexible for testing while still using the generated classes.

      • >> Is it possible to convert an ObjectContext to a DbContext so that it can be passed in to the GenericRepository constructor? << Yes, it is – DbContext context = new DbContext(ObjectContext, true);

        1) and 2) and 3) are already supported. You just need to passed in the model generated from database, says, YourEntities to the constructor GenericRepository(ObjectContext context) then use the repository. For 4) I think you need a tool to do that, not sure EF designer already support it though.

      • For anyone trying the database-first or model-first approach as a hybrid:

        I just ran into an issue where it says “Could not find the conceptual model type for _____”. Turns out that the default code generation for EDMX won’t work in the same project with anything that’s running code-first.

        Details are at http://social.msdn.microsoft.com/Forums/en/adonetefx/thread/4d9846a0-f890-41df-9444-cf2b4d2bd710?prof=required if you’re interested. You CAN use the DbContext code generator based on your EDMX model since that template generates POCOs rather than the EntityObject based classes from the default template.

  4. Really well done! Thanks again!

  5. Very cool sir. I had to modify a few things for DI but still way cool

  6. Hi Huyrua,

    De current release does not implement IsSatisfiedBy(TEntity entity) on the Specification. Is there a particular reason for that?

    I’ve added it in my code and I’m using it.

    Another question, about your approach on Specification, is: Why not to have several specifications on a single class? Probably this is a dumb question 😛

  7. Great job, just in time for my upcoming project. Thanks.

  8. Thank you huyrua for great work.

    I have one question that I am not able to solve on my own – I would like to perform ordered query, and can not find proper way how to do it.

    The only method that looks like it could perform it is IRepository.Get, but when I write something like:

    rep.Get( i => i.InvoiceDate, 0, 1, SortOrder.Descending );

    I get error on i.InvoiceDate that it “Cannot convert expression type ‘System.DateTime’ to return type ‘string'”. Is there a way for me just to specify the class field and use it to get ordered list like with the “normal” LINQ queries?

    Thanks in advance for the answer.

    • Pantelija,

      You might want to check out this comment from cconway25: https://huyrua.wordpress.com/2010/12/16/entity-framework-4-poco-repository-and-specification-pattern-upgraded-to-ctp5/#comment-235

      The point here is: if you want to perform ordered query on a property which is _not_ of type string, you must add an overloaded method like the following (as the suggested from the given comment):

      IEnumerable[TEntity] Get[TEntity, TOrderBy](Expression[Func[TEntity, TOrderBy]] orderBy, QueryOrder queryOrder, int pageIndex, int pageSize) where TEntity : class;
      return GetQuery[TEntity]().OrderBy(orderBy).Skip(pageIndex).Take(pageSize).AsEnumerable();

      and call it like this:

      var output = repository.Get[User, int](x => x.Id, QueryOrder.Ascending, 0, 5).ToList();


      var output = repository.Get[Product, double](x => x.Price, QueryOrder.Ascending, 0, 5).ToList();

      Hope this helps.

  9. Question about the base Entity class.

    Most samples I saw has a simple int Id in the base class. But in this example http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx it defines

    public abstract class DomainObject
    public override sealed bool Equals(object obj)
    public abstract override int GetHashCode()


    public class Customer : DomainObject, IHasAssignedId
    public class Order : DomainObject

    This seems quite useful since my classes have a mix of string and int ids, some are assigned like employee id, others are simple identity field.

    Do you foresee any issues for this to work with EF code first and your framework? Thanks.

    • Sorry, doesn’t take bracket, trying [pre]

      public abstract class DomainObject
      public IdT ID {}
      public override sealed bool Equals(object obj)
      public abstract override int GetHashCode()
      ... ...
      public class Customer : DomainObject, IHasAssignedId
      public class Order : DomainObject
    • Sorry, here it is again using [ ]

      public abstract class DomainObject[IdT]
      public IdT ID {}
      public override sealed bool Equals(object obj)
      public abstract override int GetHashCode()
      … …

      public class Customer : DomainObject[string], IHasAssignedId[string]
      public class Order : DomainObject[long]

    • @Whoever,

      If your entities’ ids are mix of type, the simplest approach is not let them inherit from Entity base class in Infrastructure.Model. Each entity should have an Id property that is of the desired type. Also, remember to map the Id to the appropriate column in the [Entity]Mapping class, for example:

      public class CategoryMapping : EntityTypeConfiguration
      public CategoryMapping()
      HasKey(x => x.Id);

      Property(x => x.Name);

      // Other mapping statements..


      Hope this helps.

  10. Dear Mr. Nguyen,
    Marvelous piece of code. It simplefied a lot of things for me. Especially with EF4.1.
    I however got one small question/comment. I tried to use the following code where the context
    is the current one from the contextmanager. I did this in your tests.

    string script = (IObjectContextAdapter)ctx).ObjectContext.CreateDatabaseScript();

    The result of the script give all singlular tablenames while I was expecting plural names. I also did the test with my own configuration and also there the tablenames where singular while I also used the .ToTable function to give them special names?? I was hoping that you could explain me what I’m doing wrong.

    Thanks again for your plendid work and sharing it with us
    Leonard Wennekers

    • I am not sure what your scenario is. Here is what I tried by writing some tests in the Infrastructure.Tests project:

      1) In CategoryMapping class (Infrastructure.Tests.Domain.Mapping\CategoryMapping.cs), I changed the table name to Categories (plural) by this line of code: ToTable(“Categories”);
      2) Added a test method GenerateDatabaseScript() to class UseMyDbContextTest (Infrastructure.Tests.Data.Lab\UseMyDbContextTest.cs) like below:

      public void GenerateDatabaseScript()
      string script = ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript();
      // for debugging

      The output to the console after running the test was (just some excerpt):

      create table [dbo].[Categories] (
      [Id] [int] not null identity,
      [Name] [nvarchar](max) null,
      primary key ([Id])
      create table [dbo].[Customer] (
      [Id] [int] not null identity,
      [Firstname] [nvarchar](25) not null,
      [Lastname] [nvarchar](25) not null,
      [Inserted] [datetime] not null,
      primary key ([Id])

      I could see that the script was generated with expected table names specified in the mapping class: Categories (plural) and Customer (singular), etc.

      You can try it your self and let me know the result.

      Hope this helps.

      • Dear Mr. Nguyen,

        Thanks for your fast response. I looked into my problem a little deeper and I foud out that that SqlServer connections are doing it all correctly. I was however using a Firebird dataprovider when I ran into this problem and I found out that the provider I was using got some bugs. I could even see is inside the available source code. So Im going to write them a bugreport.
        Thanks again for looking into my problem I really helped me to find the real problem.

        Best regards

  11. This is really great code and saved me a ton of time. Just wanted to say thanks.

  12. Hey huyrua,

    I’ve just started playing around with your framework and so far its pretty impressive, so nice work. One of the things i’m aiming for is to try and abstract away the underlying implementation of my data layer so that my mvvm code does not have to reference any EF libs at all and does everything via your framework.. The Repository interface you’ve provided is great for this, however i’m struggling with handling concurrency exceptions.

    As we all know, when a concurrency exception occurs a Concurrency Exception is thrown in SaveChanges of the UnitOfWork class. At the moment I’m catching it in my ViewModel ‘save’ code and dealing with it there, which is not ideal as it means my MVVM layer needs to reference EF (since the Concurrency Exception lives in System.Data.Entity.Infrastructure), thus creating a dependency directly to EF.

    So i guess my question is, where you put your concurrency handling logic to prevent this?


    • My 2 cents opinion: catch ConcurrencyException in the SaveChanges method of UnitOfWork then create a new exception class, says DbConcurrencyException and throw it out. The class DbConcurrencyException may be implemented in the Infrastucture.Data so your MVVM class can refer to it instead of directly depending on System.Data.Entity.Infrastructure.

      • Yeah that’s what i was thinking but thought I’d ask in case there was a fancier way.


  13. Hi Huyrua
    Please I have two questions regarding the GenericRepository that uses DbContext:
    1. I see that the update method was not implemented. is there any reason for that?

    2. in the build method of DbConterxtBuilder you have this line of code

    retrun (T) new DbContect(cxt, false); Please would you explain this code? T representes a class which derives from DbContext. that is

    class T:DbContext { }

    How is it then possible to cast the base type to type T when the created object is of the base type?



    • Raymond,

      1) The reason for not implementing Update method on GenericRepository which uses DbContext is DbContext does not have Update method. Also, I rarely use the Update method on Repository but SaveChanges after making changes on the POCO objects. Anyway, I have added the implementation for the Update method, but you can only see it by getting the source code from google code’s svn – http://code.google.com/p/ef4prs/source/checkout – because it is currently not included in the download list.

      2) I cast the DbContext to T because if we don’t, the code is not compilable.

  14. Huyrua,

  15. When you cast your context to the ObjectContext, I can see an issue with the SaveChanges method:

    Reason being, is if you override the SaveChanges in your _dbContext it will not be hit because you are casting it as an ObjectContext. Unless you can handle that in your UOW?

    • Not sure what you meant but from my test code (the newly added UpdateProduct() method to be specific), either UoW.SaveChanges() or UoW.BeginTransaction() then UoW.CommitTransaction() works as expected. Here is the extracted test code for both scenarios:

      1) Call SaveChanges() on the UoW

      private void UpdateProduct()
      var output = repository.FindOne(x => x.Name == "Windows XP Professional");

      output.Name = "Windows XP Home";

      var updated = repository.FindOne(x => x.Name == "Windows XP Home");

      2) Or use transaction with UoW

      private void UpdateProduct()
      var output = repository.FindOne(x => x.Name == "Windows XP Professional");

      output.Name = "Windows XP Home";

      var updated = repository.FindOne(x => x.Name == "Windows XP Home");

      You can check out the latest source code at http://code.google.com/p/ef4prs/source/checkout and play around. In my experiment, both methods result the product name is updated to “Windows XP Home” in the database.

      Am I missing something?

      • Yes, it works, but I am specifically talking about if you were to override the SaveChanges in your derived DbContext class. Here is an example:
        public class SomeContext: DbContext
        public DbSet Addresses { get; set; }

        public override int SaveChanges()
        foreach (var entry in ChangeTracker.Entries())
        var entity = entry.Entity;
        if(entry.State == EntityState.Added)
        entity.DateCreated = DateTime.Now;
        entity.DateModified = DateTime.Now;


        if(entry.State == EntityState.Modified)
        entity.DateModified = DateTime.Now;

        return base.SaveChanges();


        In the UnitOfWork class, since you are casting the DbConext to an IObjectContextAdapter, the overrided SaveChanges method in my context example above, will not run. Does this clarify what I was saying?

      • The reason for casting DbContext to ObjectContext is that ObjectContext’s SaveChanges() method allow us to specify the SaveOptions parameter that I think it is more flexible. You can see the idea at the override SaveChanges(SaveOptions) method. I just want to be consistent on calling saving changes on either DbContext or ObjectContext.

        In your case, I understand the need to override the SaveChanges method on derived DbContext object to update the DateCreated and DateModified on an entity before saving changes. That said, I think you might need to change the implementation of the SaveChange() method of the UoW class to let it call the SaveChanges() on the DbContext instead of ObjectContext. In short, you can change this line:




        Hope this helps.

  16. Using “DBContext”in this way, does not return data relationships.
    Any Idea?


    Private Repositorio As IRepository
    Private DbContext As MyDbContext

    DbContext = New MyDbContext(“DefaultDb”)
    Repositorio = New Infrastructure.Data.EntityFramework.Lab.GenericRepository(DbContext)

    Dim Categoria As Category = Repositorio.FindOne(Of Category)(Function(d) d.Id = 1)
    Dim products As IList(Of Product) = Categoria.Products


    products count zero, and I dont Know why. The database was created fine, I’m using the mapping of the example and the same models.

    The data are in the database, are correct, relationships and the “primary key and foreign key” as well.

    • Good question, Viure.

      I figured out that we have to specifically load Products when loading Category. Otherwise, the Products count is always zero.

      I made a following test code to demonstrate how to load Products with Category using the Include extension method which was added to EF 4.1 version


      public void Test()
      DoAction(() => FindCategoryWithInclude());

      private void FindCategoryWithInclude()
      var category = repository.GetQuery(x => x.Name == "Operating System").Include(c => c.Products).SingleOrDefault();
      Assert.Greater(category.Products.Count, 0);

      Hope this helps.

      • Watching Now Include documentation in the Entity Framework, I’ve realized how it works. I come from a repository using LinqToSql and easier and I assumed that this was carrying the relationships.

        Thanks for the help.

  17. If i´m using this in my DataContext:

    Public Property Eventos() As DbSet(Of Evento)

    modelBuilder.Conventions.Remove(Of IncludeMetadataConvention)()
    modelBuilder.Conventions.Remove(Of PluralizingTableNameConvention)()

    in the model mapping EventoMapping.vb


    Then, Why in GenericRepository , function GetEntityName:

    _pluralizer.Pluralize(typeof(TEntity).Name) (returns Eventoes ( Thats because Language, ok ))

    typeof(TEntity).Name (returns Evento , when i was waiting “Eventos”)

    I´m doing something wrong,without Pluralization the mapping table Name override the Name?

    • The pluralization being used here has nothing to do with the underlying table names, it’s there to help identify an entity name managed internally by ObjectContext (combined with ObjectContext.DefaultContainerName). In other words, it does not rename the table name, but the ToTable(“[TableName]”) in the mapping class does.

  18. Hi,
    Nice code!

    Is it possible to use it directly in a IHttpModule rather than HttpApplication ?
    I tried to do so in a WebDAV project that implement IHttpModule but obvisouly it’s not working…

    Thanks in advance for the reply

    • I am afraid it’s not.

      The reason for using HttpApplication class here is that we want to hook into BeginRequest and EndRequest events to Open and Close the DbContext or ObjectContext (this is also known as Open Session In View design pattern)

      I am not familiar with WebDav as well its development model and/or request life cycle so I don’t have strong opinion here. But via this article http://support.microsoft.com/kb/307996 I think it is possible although I haven’t tried it yet.

  19. Hi Huyrua,
    Thanks a lot for giving us speed to use EF with DDD patterns. Like many other I follow your blog and using your patterns.
    I am using your framework for my MVC3 Web-App, and want to keep latest of your project. I have one small issue:-
    I want to use database connection string based on user’s choice of Database, which he make using Login Process. But DbContextManager.Init accepts only connectionStringName. I can modify method to accept modified connection string, but I afraid, It will be little problematic to add your new version of projects.. Can you please update DbContextManager.Init() method to accept connection string also.
    Many Thanks 🙂

  20. Hi Huyrua,
    Could you please help me with this error, not sure what I am doing wronge:-
    I am getting an exception with message:-
    Unable to determine the provider name for connection of type ‘System.Data.EntityClient.EntityConnection’.
    At line number 49 of “DbContextBuilder.cs” :-
    var dbModel = this.Build(cn);

    Web.Config Settings for Connection string and DbProviderFactories are:-

    • This above problem is solved. I was using normal EF connection string, where as I should be using simpler code first connection string without msl…tags.

  21. Hi Again,
    I am having Database already in place and using your framwork. For hours i juggled with error “Invalid column name ‘Id’… I found Id property in EntityBase class. I have Primary key created in my tables and I am defining them in Mapping classes as :-
    HasKey(x => x.ReceiptID);
    Still this error is coming.
    (For the time being i had to comment out Id proeprty of EntityBase class. Please tell me better way of doing it instead of commenting out this line of ur code. — Thanks.

    • I think not only you but others also have the same need to not use Id but more specific primary key, like ReceiptID. If that is the case, you shouldn’t inherit your entity from EntityBase class. Also, in the mapping class, just map the primary key to the column you prefer, like what you are doing with the line of code HasKey(x => x.ReceiptID)

  22. Hi Huyrua,
    I am initializing db context in my ASP.NET MVC3 app like below:- but seed is not working, any idea? Thanks. Also I am planning to use ur framework with Azure, is it ok to use it with SQL Azure.

    protected void Application_BeginRequest(object sender, EventArgs e)

    DbContextInitializer.Instance().InitializeObjectContextOnce(() =>

    Database.SetInitializer(new DataSeedingInitializer());

    DbContextManager.Init(“InsightDBContext”, new[] { HttpContext.Current.Server.MapPath(“~/bin/Insight.CloudWeb.CloudDB.dll”) },true);


  23. Firstly, I must say excellent work! I’ve been working with your framework in several projects over the last few months. I was happy to see the change regarding the specification pattern/repository not fetching full results and then applying filters.

    However, this does bring up an issue I’ve come across in implementing the change. If I Add new entities to the repository, the new version of GetQuery doesn’t return those additions unless Save is called. I need/want to be able to query including the changes before committing those changes.

    Is there a suggestion to how this can be accomplished?

    • I have had this experience too. It differs from how EF itself is working. I also had a transaction issue – if I wrap some operation in a TransactionScope, the DbContextBuilder.BuildDBContext() chokes on if (!ctx.DatabaseExists()). A first guess is that what goes wrong is that the “autogenerate database when building DbContext” shouldn’t live in that method – I mean, if a method should do one thing, then creating and deleting databases is a rather extreme side effect to a method named BuildDbContext – what is does now is more like CreateDbAndBuildDbContext.

      Since I prefer to wrap my unit tests in transaction scopes and roll back at the end rather than deleting and recreating the test database, I will look into this in the coming week 🙂

  24. Hi – I have been grappling with a small problem around a custom specification inheriting from your ISpecification.

    The custom specification takes an ICustomer, so that it can be tested without using a real Customer.

    However when I try GetQuery(MySpecification), try as I might, I cannot successfully get IQueryable to work. The nearest I got was changing to MySpecification where T:ICustomer but still got an EF error when defferred execution took place: “Linq to Entities only supports casting Entity Dta Model primitive types”.

    Any ideas? Don’t really want to base my specifications on concrete types if I can help it…

  25. Hi,
    lately I have been working on application taking advantage of your great solution (thank you for the articles by the way, they are really helpful). In my model I defined tables with schema name using method ToTable(tablename, schemaname) within mapping classes.

    The problem is that when I try to use ObjectContextManager instead of passing context to the repository, I get an exception because created query is trying to retrieve data from table with correct name but “dbo” schema instead of custom one defined in mapping class. Is there any way to make it behave properly?


  26. Ok, another interesting thing. I’ve downloaded your solution (ef4prs-1.4-src) and just modified table creation for customer: ToTable(“Customer”, “Customers”) in CustomerMapping class. Then I’ve run RepositoryTest and it turned out that table Customer has been created in dbo schema instead of Customers.

    Is that a kind of bug or am I doing something wrong?


    • Fortunately I’ve managed to solve the problem by myself:

      Because I usually try to follow DRY rule, I’ve decided to declare base mapping class inheriting from EntityTypeConfiguration and thus most of other mapping classes inherits from it instead of EntityTypeConfiguration. The problem is that when ObjectContextBuilder tries to check if base class is of type EntityTypeConfiguration in such a case it is not 🙂

      Once again, thank you for your solution.


  27. I really like what you share here. Pretty easy to get up and running.

    I don’t like the structure of your project though. Lab files sort of means I need to take the time to compare versions of the same classes and decide if the non-lab-version is poor or what else the reason is for having several versions of the same files.I have never seen a similar approach for any developers who are familiar with source control management 😉

    Again, I really like what you share here.

    • Yes the code structure is somewhat not good enough to be ready for development and people may take time to compare or migrate some code when there is a new release. However, please bear with me that my idea is trying to show the possible implementation of DbContext, so there is a Lab version. I think it is impossible to create a one-size-fit-all code structure: some ones would prefer the other namespace name, for instance.

  28. I found an issue when using GetQuery().
    It will always retrieve the entities already in memory. If I need to refresh those entities from the database, what can I do?
    Any solutions?


    • I think I’ve found a solution to my problem.
      I’ve changed the GetQuery implementation to:

      var entityName = GetEntityName();
      var query = ((IObjectContextAdapter)DbContext).ObjectContext.CreateQuery(entityName);
      query.MergeOption = System.Data.Objects.MergeOption.PreserveChanges;
      return query;

      Basically, I only needed to change the MergeOption property, which has AppendOnly as it’s default.
      Oh, I forgot to mention that I’m using the “Lab” version.


  29. Hi Huyrua,

    I have been getting this error and have already tried for many hours to fix the issue.
    The property ‘Id’ is not a declared property on type ‘Employee’. Verify that the property has not been explicitly excluded from the model by using the Ignore method or NotMappedAttribute data annotation. Make sure that it is a valid primitive property.

    Code that generate exception: return string.Format(“{0}.{1}”, ((IObjectContextAdapter)DbContext).ObjectContext.DefaultContainerName, _pluralizer.Pluralize(typeof(TEntity).Name));

    I have an EntityBase class that declares an Id property public virtual long Id { get; set; }
    and another class ‘Employee’ that derives from EntityBase and a third level class Manager that derives from Employee.
    In my ManagerMapping class i have HasKey(x => x.Id);

    I am guessing that Property Id from EntityBase class is not getting reflected in Manager class.
    However, If i derive Manager class directly from EntityBase class it works fine.

    Please advice.

    Thanks in advance

  30. I think there’s nothing wrong with your inheritance and mapping stuff. The problem is with the code that gets entity name. At the moment I don’t have a solution for this. Will do some research on this when I have time.

  31. Do you have a sample of mocking the generic repository for testing?
    I wanted to make my code testable using your approach, but I’m stuck…


  32. I would very much like to use your framework but I am having a problem getting it to work in ASP.NET MVC3. I already had a database so I used EF4.1 to create the ADO.NET Entity Data Model. VS2010 generated the edmx file and the underlying Designer.cs file. I noticed that the class named after the db table is derived from EntityObject and that causes the following line of code to fail:
    var dbModel = this.Build(cn);
    If I can’t use these model definitions is there another tool that will generate the model and mapping source files?

    • Since you are using database first development by generating the model from an existing database, you don’t need to use the ObjectContextManager or DbContextManager at all. All you need to do is passing in the instance of generated ObjectContext (found in the edmx.cs) to the GenericRepository:

      var context = new YourObjectContextName();
      GenericRepository repository = new GenericRepository(context);

      You can look at the property ObjectContext in the GenericRepository class to how it gets the ObjectContext (or DbContext). Also, there is a test code that shows how database first development works with this framework at Infrastructure.Tests\Data\Lab\UseMyDbContextTest.cs

      Hope this helps.

      • That is what I was missing. Also, for anyone else who reads this, you still need to create the mapping file for each data model and implement the commented out code that is in WebObjectContextStorage.cs within your Global.asax.cs file.

        Keep up the good work, Thanks!

  33. I have a table of statuses that is shared (joined) by many tables (order, shipment, rma) that I filter on. The issue is that the order and shipment tables do not contain any reference to the statuses table and the statuses table contains a reference to the order or shipment table loosely using two columns (one to specify the referenced table name, like order, and the 2nd column for the referenced table ID). The referenced table ID is merely an int32 and is duplicated across the various main tables like order and shipment. I don’t know how to specify the join between these in the POCOs and when I attempted to do it in the repository as a query I get an error message at runtime: “The EntitySet ‘TransactionResendStatus’ is not defined in the EntityContainer ‘MercuryDbContext’. Near simple identifier, line 1, column 18.”
    (where MercuryDbContext is subclassing DbContext and order and transactionResendStatus are both defined but without navigation references to each other.
    Not sure how to model this.

    • I guess the error comes from you haven’t put a DbSet[TransactionResendStatus] property to MercuryDbContext, like: public DbSet[TransactionResendStatus] TransactionResendStatuses.

      • but I DO have that defined:
        public class MercuryDbContext : DbContext
        public DbSet[TransactionResendStatus] TransactionResendStatuses { get; set; }

        // Orders
        public DbSet[Order] Orders { get; set; }
        public DbSet[OrderLine] OrderLines { get; set; }
        public DbSet[OrderPayment] OrderPayments { get; set; }

        … and it is in the OnModelCreating(…) for the mapping…

        here is my retrieval method in my OrderRspository. This works in LinqPad (with slight mods to access the tables directly instead of the GetQuery POCOs ):

        public Order FindDynamicsSuccessfulOrderByOrderID(string marketCode, string orderID)
        int[] resendStatusList = new int[] { 1, 2 };

        var orders = GetQuery()
        soh => soh.ID,
        trs => trs.ReferenceTableID,
        (soh, trs) => new { soh, trs })
        temp =>
        ((((temp.trs.ReferenceTable == “SalesOrderHeader”) && (temp.trs.IdentifierID == orderID)) &&
        (temp.trs.IdentifierType == Utilities.IdentifierType.Order)
        ) &&
        .OrderByDescending(temp => temp.soh.ID)
        .Select(temp => temp.soh)

        if (orders != null && orders.Length > 0)
        return orders[0];
        return null;

        Here is the error:
        The EntitySet ‘TransactionResendStatus’ is not defined in the EntityContainer ‘MercuryDbContext’. Near simple identifier, line 1, column 18.

      • I know this is an old thread, but I ran into a similar issue today. This article was one of the few areas which matched my search on google…
        Chad, I noticed that your class “TransactionResendStatus” was named similar to mine in that they both ended with the word “Status”. This got me thinking there may be something wrong with the pluralize capabilities in EF/POCO template. Since status is an odd pluralization “Statuses”
        I renamed my class removing the word “Status” and everything worked as expected, reanmed it back to have the word “Status” and it blew up. Gonna dive in deeper to see if I can find the root cause.

      • I ran into the same issue. I have a domain (poco) object simply named Status. In my context class, it is wired up as follows:

        public DbSet Statuses { get; set; }

        This causes the exception “The EntitySet ‘Status’ is not defined in the EntityContainer ‘MyDbContext’.”

        Modifying the context class as follows corrects the problem:

        public DbSet Status { get; set; }

        I am using EF 4.1. I hope this helps someone.

  34. hi huyrua

    in the BuildObjectContext from the ObjectContextBuilder class, you execute “dbModel.Compile().CreateObjectContext(cn)” each time there’s a new request to the server.

    could it be a good idea to cache “dbModel.Compile()” somewhere and only have to create the ObjectContext on new Request?

    also, is there any trick to plug MvcMiniProfiler with your framework?

    thank you for your help!

    • Alex,

      Actually, the ObjectContext is managed by ObjectContextManager. Every time the repository needs ObjectContext, it pull ObjectContext from ObjectContextManager.

      The ObjectContextManager, when being asked for ObjectContext, it will then look for ObjectContext in the (Web)ObjectContextStorage. If there is no ObjectContext in the storage, it calls ObjectContextBuilder.CreateObjectContext() then stores the newly-created ObjectContext in the storage.

      The flow described above means that the ObjectContext is lazily created and stored for later use, it is not created everytime we need an ObjectContext.

      I dont know how MvcMiniProfiler works just yet, so I dont have an answer here.

  35. Usage of this framework on Worker Role of Azure. Constructor of WebDbContextStorage accepts of type [HttpApplication] which would not be available in Worker Role. Any suggest about how to handle it…Thanks.

    • I don’t have any experience on Azure, so I don’t have strong opinion on this. But I hope you understand the idea for using HttpApplication to hook for BeginRequest and EndRequest, then you can find an alternative object to do this in Azure.

  36. huyrua, when i run my web application, the code execute objectContextBuilders[key].BuildObjectContext() on each new server call so the ObjectContext get created on each request.

    If i ask the ObjectContext many times in ONE request, then the BuildObjectContext() get called only one time.

    This is not what you get on your side?

    • Oh yes, Alex. I just verified and you’re right.

      I did some experiment and this is the way to cache the object context creation that you might consider:

      In ObjectContextManager class, declare a private memmer as below:

      private static Dictionary[string, ObjectContext] _objectContextCache = new Dictionary[string, ObjectContext]();

      Then in the code that retrieves the ObjectContext of ObjectContextManager, I update it as below:

      // other code…

      context = _storage.GetObjectContextForKey(key);

      if (context == null)
      if (_objectContextCache.ContainsKey(key))
      context = _objectContextCache[key];
      context = _objectContextBuilders[key].BuildDbContext();
      _objectContextCache.Add(key, context);
      _storage.SetObjectContextForKey(key, context);

      //other code…

      Let me know if you have any question/suggestion.

  37. How do you search a list and its collection with this repository and EF framework? Let’s say I have Author and each has a list of books. I want to search name and title, like this:

    SELECT * FROM Authors a LEFT JOIN Books b ON a.UserId=b.UserId
    WHERE UserName LIKE ‘%this%’ OR BookName LIKE ‘%that%’

    With native EF dbcontext, it seems you can do something like

    var result = from myDbContext.Users join myDbContext.Books …

    But I have no clue how this can be done using repository. Can anyone help? Thanks

    • Try this:

      IEnumerable authors = Repository.Find(x => x.UserName.Contains("this") and x.Books.Any(y => y.BookName.Contains("that"));

      • Thanks. Wasn’t paying ANY attention 🙂

        The only problem I can see is that for every “that”, it generates a sub query “OR EXIST (SELECT .. JOIN WHERE id=id and Name like ‘%that%’)”. So if you check 3 properties in Books, it creates 3 subqueries with joins. Might be a problem for more complex queries. And speaking of performance, after adding all the query conditions and .Include(x=>x.Books), the original 600 bytes hand crafted SQL bloated into 5K+ by EF!

        I know there’s a ExecuteStoredQuery and I can use fill an ad hoc view object. But is there a way to feed handcraft SQL result set directly to EF/Repository/Entities? So I can do something like Respository.GetQueryBySQL(“SELECT …”), but still let the framework take care of mapping tabular result into hierarchical POCOs?

    • I won’t promise anything but will try to find a way to expose ExecuteStoredQuery from repository in the next release.

      • I’m in a situation where it would be very helpful to have ExecuteStoredQuery available. I realize this breaks the repository pattern a bit, and it will be very difficult to test an arbitrary SQL request. Still, sometimes life happens and you just need access!

        In the meantime, I’m debating between two thoughts: 1) Modifying your code to make the ObjectContext protected instead of private, then inheriting from GenericRepository and using the ObjectContext property directly to access my stored procedures; or 2) Using ObjectContextManager.CurrentFor() to bypass the private ObjectContext property.

        Any thoughts on a “preferred” work-around for now?

      • I am in that situation too. I will let you know when I finished the implementation for this.

  38. Hi Huyrua,
    Few small suggestion for Update method:-
    1. Can it return bool. true of record found and updated else false:-
    public bool Update(TEntity entity) where TEntity : class
    var fqen = GetEntityName();

    object originalItem;
    EntityKey key = ((IObjectContextAdapter)DbContext).ObjectContext.CreateEntityKey(fqen, entity);
    if (((IObjectContextAdapter)DbContext).ObjectContext.TryGetObjectByKey(key, out originalItem))
    TEntity entity11 = ((IObjectContextAdapter)DbContext).ObjectContext.ApplyCurrentValues(key.EntitySetName, entity);
    return true;
    return false;
    2. check to see if object exist, internally firing query which fetches ALL the columns, could slow down the bulk update , for same purpose,do we have something more efficient than :-
    (((IObjectContextAdapter)DbContext).ObjectContext.TryGetObjectByKey(key, out originalItem))

    (.Any() can help here?)

  39. Miguel De Lathouwer

    Awesome post, really useful, but when I used this repository in a batch process whereby multiple threads are accessing the repository along with the simple objectcontext storage, I got exceptions since an objectcontext cannot be shared (EF is by itself not threadsafe due to this). Therefore, with a small modification to the SimpleObjectContextStorage it seems to work now as well: I simply made the storage variable threadstatic and used the property in the other methods instead (_storage is duplicated per thread, but only filled in for the first thread via the static constructor call)
    [ThreadStatic] private static Dictionary _storage;

    private static Dictionary Storage
    get { return _storage ?? (_storage = new Dictionary()); }
    note: ThreadStatic expects the corresponding variable to be static as well, but since you typically define only one storage per app via the ObjectContextManager.Init call, this shouldn’t have an impact.

  40. A great framework! Thanks for sharing.

    I am playing with your framework and I found something interesting. The implemented specification pattern is working perfect. So I have a service layer that make queries and uses specifications to filter data. I did a quick and simple test by calling the service in a Console application. The generated SQL is what I expected that is the filter is applied in the database and not in-memory and only ONE query was made. However, when I use or call the service method through WCF, EF makes multiple queries, instead of one query with the filter defined in the specification. I was wondering why the same code behaves differently.

    • How do you manage ObjectContext/DbContext in Wcf? Make sure to implement a WcfObjectContextStorage (or WcfDbContextStorage of you’re using DbContext) to return only one instance of ObjectContext (or DbContext) per Wcf call.

  41. Hi Huyrua

    Finally managed to post!

    Thanks for all your hard work on the repository and specification patterns; very helpful to me on my tight deadline.

    I do have a query with the EF4.1 Lab version of UnitOfWork as I cannot start a new transaction after rolling back the previous one. I noticed that in CommitTransaction there is a call to ReleaseCurrentTransaction, which sets _transaction to null. No such call exists in RollBackTransaction and I wondered if this could be a mistake or if I am misunderstanding something.

    I know some people create a new repository for every operation but I have loaded many entities and wish to continue with the same one.

    Thanks again


  42. I was trying to use Linqpad beta http://linqpad.net/Beta.aspx, open my main entity dll and play around with linq queries.

    First it complains there’s no DbContext, I added one just for test sake.

    Then it says there’s no primary key on the entity because it can’t recognize the fluent definition in EntityTypeConfiguration. So I added a dataannotation key attribute.

    Now it keeps trying to query EdmMetaDatas which doesn’t exist since I manually created the database.

    Any idea how Linqpad can work with the code-first-entities-repository approach we have here? Thanks.

    • I don’t have experience on Linqpad so I don’t have strong opinion on this. Please experiment it yourself and maybe share your experience with us.

  43. For some reason the comment I left yesterday has been removed, so let me ask again. I am having problem moving the repository-call code into another project.

    The following code works in my test project.
    private void button1_Click(object sender, EventArgs e)
    var count = this.repo.GetAll().Count();


    Now I want to move the this.repo.GetAll code to a project with a class defined as:

    public class GenericTask where T : IEntity
    public IRepository repository;

    public GenericTask() { }

    public GenericTask(IRepository repository)
    this.repository = repository;

    public T Get(Guid id)
    return repository.Get(id);

    public IEnumerable GetAll()
    return this.repository.GetAll();

    How can I implement IoC here when ObjectContextManager is a static class.

    • If youre using an IoC container, you must first register the GenericTask as well the Repository with the container in the application bootstraper, e.g.



      Then in the code that use GenericTask you can call like below:


      That call will tell the container to resolve the GenericTask as well inject the dependency on IRepository to it.

  44. Hi Huyrua,

    Excellent to see this framework still continue to grow and evolve! I picked it up again recently and I have a question for you if you please. Here’s what I did:

    -when testing out WebDbContextStorage (i.e. the context of a web application)
    -open up two separate browser instances; probably two different browsers is best, for total separation
    -now, in one of the browsers, perform a data operation of some sort using the repository which is sufficiently intensive (e.g. put lots of dummy data in a table) that it takes maybe 5-10s to complete
    -while the first operation is running, perform another data operation (can be the same one) which similarly takes a long time to complete

    The important point is that we are trying to simulate the experience of two separate users on a site requesting data concurrently. Surprisingly enough, when I try this, the second user to begin the data operation always errors out with the following error:

    There is already an open DataReader associated with this Command which must be closed first.”

    Basically, it seems like the user who starts later “loses out” in some kind of contention scenario. Is this something that you are able to replicate? If it is, any ideas on how to resolve?

    Thanks for great work!

    • Each user owns his request, as well has his own ObjectContext (or DbContext if you prefer to use it over ObjectContext). So I think there should not be the concurrent issue. Can you make sure you has initialized the ObjectContectManager (or DbContextManager) in the Application_BeginRequest?

      • You know what, I had actually not added the initialization steps in Application_BeginRequest as you describe. However, adding that didn’t make a difference unfortunately – I still get the error. (Even without having the initialization steps in that event, everything works perfectly for a single user, because I had performed the initialization at an earlier step, in Application_Start.)

        One thing I’d like to ask: in the example in the comments of WebObjectContextStorage, in Application_BeginRequest, the initialization calls are made through:


        I’m curious about this. Since everything goes through InitializeObjectContextOnce, and that class, a singleton, has a flag which only permits one-time initialization (like its name), what is the reason for calling it every time in Application_BeginRequest if it will only actually do anything during the first request for the first user?

      • If youre using this framework in a web application, I think the most critical part is you have to create WebSessionStorage during the Init() to tie in HttpApplication events as well initialize the context manager once on Application_BeginRequest. This is for managing the object context life cycle which is called “Open Session In View” coming from java world to manage the session life time. Its a long story that I hardly explain fully here Please also do so in your application then let me know whether the problem still remains.

  45. hi huyrua

    I have just started using your framework.
    I took the latest source code Apr 13 2011 opened the project and compiled such.
    The test project threw and error / to the effect that it need edto be run from another project.
    I then added a WPF project to the soluton. Made that the startup application.
    Everything worked fine.
    I then added reference to all the projects except Infrastructure.Tests.

    My project will address anything defined within Infrastructure.Data or Infrastructure.model
    but will not see Infrastructure.data.EntityFramework.

    I have included this in my references.

    “Using Infrasture.Data.EntityFramework” shows as an error.

    I am unable to continue

    this code : ObjectContextManager.InitStoreage….. shows an error because the using clause above does not get accepted.

    Could you give some pointers as to how to resolve.
    kind regards JulianH

    • There may be a conflict with the name Infrastructure.Data.EntityFramework with the EntityFramework.dll itself. I am not sure.

      If you plan to use this code in production, consider changing the namespace of Infrastructure.Data.EntityFramework to another name, e.g. Infrastructure.Data.EF. Yes I know this is inconvenient but please bare with me that the framework you are downloading is just for demonstrating the patterns apply for EntityFramework.

      I ‘d like to share my experience working with this framework: I move all the code in the Infrastructure.Data.EntityFramework\Lab to the Infrastructure.Data as well rename all the namespace Infrastructure.Data.EntityFramework.Lab to Infrastructure.Data because I prefer using DbContext to ObjectContext. Then in the application code I only need to add refererence to Infrastructure.Data.

      Try it then let me know if you till have problem with it.

  46. Hi huyrua,

    First of all I appreciate this framework, it was a big help!

    Now that Code First Migration is coming soon (its now in it’s alpha 3 release), I’m curious about how can you add migration in this framework while the model evolve.

    Best regards,

  47. Man! That’s a hell of a good work!! =PP

    But what do i need to do if i’m using the Generated POCO and context with T4 ????

    Can i use the WebDbContexStorage thing with that??

    Im getting lots of errors…

    How can i use my context with that?


  48. Not sure if I understand this correctly. Let’s say I have

    userRepository = new userRepository();
    auditRepository = new auditRepository();

    They actually share the same context created by objectcontextbuilder (using “DefaultDb”), right? So if I do


    Both changes should be made and in a transaction, is it? When do I need to explicitly using userRepository.UnitOfWork.BeginTransaction… When I run SQL profiler, I don’t see an explicit transaction on SQL side. Not sure how exactly this works.

    Sorry for dumb question, still new.

  49. Hey!

    There’s a bug on your Get methods on the repository.

    They are skipping the pageIndex, not the PageIndex * pageSize.

    THe code should by like:

    return GetQuery().Where(predicate).OrderBy(orderBy).Skip((pageIndex-1) * pageSize).Take(pageSize).AsEnumerable();

    Using: .Skip((pageIndex-1) * pageSize)


  50. Hi Guys,

    Please help on my problem. I experiencing problem in mapping field name with white space. example. [Country Code]– declared field name in table. I hope somebody can help me.


    • Property(x => x.ColumnName).HasColumnName(“Column Name”);

      You can try this with the CategoryMapping class in test project (Infrastructure.Tests.Data.Domain.Mapping\CategoryMapping.cs). I did a quick test with Property(x => x.Name).HasColumnName(“Category Name”); and it works.

  51. Hi Guys,

    Any one can help me on my problem.

    —— Test started: Assembly: PMU.DataAccess.Data.EFTest.dll ——

    Test ‘PMU.DataAccess.Data.EFTest.Repository.RepositoryTest.Test’ failed: System.Data.EntityCommandExecutionException : An error occurred while executing the command definition. See the inner exception for details.
    —-> System.Data.SqlClient.SqlException : Invalid column name ‘Circuit_ID’.
    Invalid column name ‘Country_Code’.
    Invalid column name ‘Date_Received_ATT’.
    Invalid column name ‘Date_Received_BrSC’.
    Invalid column name ‘Dummy_Order_Approved’.
    Invalid column name ‘Dummy_Order_Number’.
    Invalid column name ‘From_Date’.
    Invalid column name ‘IDWT_Ticket_ID’.
    Invalid column name ‘Invoice_Date’.
    Invalid column name ‘Invoice_Number’.
    Invalid column name ‘KID_Number’.
    Invalid column name ‘Net_Amount’.
    Invalid column name ‘Payment_Due_Date’.
    Invalid column name ‘Period_MM’.
    Invalid column name ‘Period_YYYY’.
    Invalid column name ‘Send_to_AP’.
    Invalid column name ‘Status_E_Type’.
    Invalid column name ‘Status_II_Type’.
    Invalid column name ‘Supplier_Code’.
    Invalid column name ‘Tariff_Code’.
    Invalid column name ‘Tariff_Description’.
    Invalid column name ‘Tax_Amount’.
    Invalid column name ‘Tax_Code’.
    Invalid column name ‘Tax_Percentage’.
    Invalid column name ‘To_Date’.
    at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
    at System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
    at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
    at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator()
    at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
    at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
    Repository\RepositoryTest.cs(44,0): at PMU.DataAccess.Data.EFTest.Repository.RepositoryTest.FindAll()
    at lambda_method(Closure )
    Repository\RepositoryTest.cs(54,0): at PMU.DataAccess.Data.EFTest.Repository.RepositoryTest.DoAction(Expression`1 action)
    Repository\RepositoryTest.cs(33,0): at PMU.DataAccess.Data.EFTest.Repository.RepositoryTest.Test()
    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
    at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
    at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
    at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
    at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
    at System.Data.SqlClient.SqlDataReader.get_MetaData()
    at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
    at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
    at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
    at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
    at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
    at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
    at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
    at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)

    Executing value(PMU.DataAccess.Data.EFTest.Repository.RepositoryTest).FindAll() …
    0 passed, 1 failed, 0 skipped, took 22.73 seconds (NUnit 2.5.5).

    I hope somebody can answer my problem regarding on how to map field name whit space using EF4 CODE First. I need this badly.


    • Follow the mapping sample in the Infrastructure.Tests. I think all scenarios (one to one, one to many, many to many) are already demonstrated.

  52. hi Huyrua,

    I check that already the Infrastructure Test. This is my concern I need to map the field name that contain space.[Country Code]. How can I map this one?


    • I already answered this for your first question. Here I repeat it again:

      Property(x => x.PropertyName).HasColumnName(“Column Name that contains space”);

  53. Hi Huyrua,
    I am planning to implement this to our production. Do yoy have sample implementation using aspx? I need this one.

  54. Hi, huyrua,
    first to say excellent work. In one of your posts you have said that this framework is a pretty solid ground, that additional refactoring can be done, but that you have left it to the user, after fully understanding how things work within the framework.

    Now, its good to know how to implement Specification pattern, but why do we need this extra layering? I am new to all this stuff, so I am probably missing something somewhere. Along with common repository methods, in GenericRepository you have many other methods like: Find, FindOne, First, Single, Count, etc. All this methods already exist in linq, are part of IQueryable, so why do we need to wrap them again? Since there is a GetQuery() method that returns IQueryable, we are able to achieve all this using Linq and lambda expressions. So why another wrapper?

    Just to be clear, I am not saying that we done need to implement repository at all, I just do not quite understand the benefit of adding above mentioned methods to common repository methods. If we wanted to prevent UI user from querying data using Linq, we can always expose a method in business layer that will take parameters for sorting and filtering collection. An example would be implementing an EntitySorter / EntityFilter implementation.

    And my second question would be: does this framework support multiple sorting? I have gone through code, there is a support for multiple where conditions, but I couldn’t find code that allows multiple sorting

    • Good questions, Goran.

      >> “Now, its good to know how to implement Specification pattern, but why do we need this extra layering?”. I don’t want to repeat the answer regarding this pattern here and there any more but here are some resources on explaining Specification Pattern and why we need it:


      >> “Along with common repository methods, in GenericRepository you have many other methods like: Find, FindOne, First, Single, Count, etc. All this methods already exist in linq, are part of IQueryable, so why do we need to wrap them again? ”

      Find, FindOne, First, Single, Count,… are convenient methods that support the users (or developers) of this framework who have less knowledge on IQueryable can easily use the repository. The GetQuery method that return IQueryable is there for some advance queries that we might want to perform when the business logic becomes more complex.

      >> “Just to be clear, I am not saying that we done need to implement repository at all”. Yes, you can choose to not implement repository at all. However, one of the benefit of repository, IMHO, is that it abstract away the complexity of an underlying ORM framework so it set the developers free from having (advance) knowledge of an ORM.

      >> “And my second question would be: does this framework support multiple sorting?”. No, it doesn’t. “One size does not fit all”. As the spirit of this framework: for demonstrating the use of EF with Repository and Specification implementation. I hope once people understand the idea and feel like they want to apply it in their development work, they can use/modify/extend it in whatever ways they can think of to suit their needs.

  55. hi huyrua,

    Can you help me on how to perform this using EF 4.1? Please see the sample query below.

    select mow.*
    from dbo.ProcessInstanceList p
    inner join dbo.AccessBillingMOW mow
    on p.ProcessInstanceID = mow.ProcessInstanceID
    where p.Status = ‘Active’

    • I think your question was asked in a wrong place since you can easily find the answers regarding Linq to Entities around the web.

  56. Sutikshan Dubey

    Hi Huyrua,
    I am using your framework extensively. I am facing some issues while doing insert/update bunch of records for set of tables. Here is my code snippet:
    foreach (….)
    GenericRepository genericRepository = new GenericRepository(connStringName);

    //Persist changes in Database of Azure
    //***code to save changes in db , throws sql exception due to some reason

    catch (Exception ex)
    logger.ErrorException(msg, ex);
    if (genericRepository.UnitOfWork.IsInTransaction)

    //now in next iteration, new set of tables try to insert/update rows in DB, but it fails due to same exception which occurred before. I want to continue with next iteration of loop forgetting rows which caused errors before. I seems it is due to usage of same DbContext, how to detach/remove those rows which caused errors.

  57. Sutikshan Dubey

    Hi Huyrua,
    for above problem of mine, I implemented RejectChanges method
    inspired from this blog – http://blog.oneunicorn.com/2011/04/03/rejecting-changes-to-entities-in-ef-4-1/#comment-48

    It solve my problem, you can verify and include it if you like.

  58. Great, where’s the VB version?

  59. First I want to thank you for your great work. I appreciate especially all your efforts to explain everthing very clear. I am learning a lot by studying all this.

    My question:
    I try to implement your solution with MVC and Windsor Castle. Should I limit the lifecycle for the GenericRepository per web request or can I define it as a singleton.

  60. I am testing a failure scenario in a UnitOfWork.CommitTransaction() and then getting the expected exception from the database. Then when I want to write a log entry downstream to record the exception I am getting the same exception from the expected one in my failure test. I have tried checking UnitOfWork.IsInTransaction in my catch block below the first exception and it reports false so I can’t see how to clear the error to move on to logging that I got an exception in the first place. If I just call RollBackTransaction() then I get “Object reference not set to an instance of an object.”
    BTW, my logging the first exception also uses BeginTransaction/CommitTransaction.
    How do I clear the first error/transaction?

  61. Hi Huy. Terrific implementation, I’d like to use it if I can get it working in the following scenario.

    I have a base class and two subclassed types.

    SiteUser: User
    FacebookUser: User

    I have 3 mapping files setup. I’m using TPT (table per type) inheritance, all I store in SiteUser and FacebookUser are properties applicable to those types of users.

    I run the project fine. I can instantiate a SiteUser and save it using your GenericRepository fine. It’s in the database. However, when I attempt to retrieve it with the following line of code I get an exception.

    _repository.Single(x => x.UserKey == guid);

    Generates exception:

    Message “The EntitySet ‘SiteUsers’ is not defined in the EntityContainer ‘CodeFirstContainer’. Near simple identifier, line 1, column 20.”

    Somebody already mentioned a similar inheritance scenario in the comments and you said you would look into it (Amit | July 12, 2011 at 9:52 pm). Based on what you said, I took at a look at the GenericRepository.GetEntityName method, but had no luck in finding the right ‘EntitySet’. I suspect if I knew EF better I could dig into the internals to see what EntitySet name it’s actually using

    Can you offer any guidance on how to solve this issue or debug further? Could you suggest a not-to-ugly workaround? Would you like me to provide more information?

    • I think if you’re using TPT then you needs to cast the returned entity to the desired type using OfType generic method. I haven’t used TPT yet so I am not quite sure how to support this scenario. Please do a little more research on this by yourself. Sorry I can’t help.

      • Thanks for the hint, Huy. I extended your solution for my specific use case. I subclassed GenericRepository to handle persistence for my subclassed entities. I overloaded GetQuery so I could pass in the type of the subclass entity on retrieval. Maybe this is something you can bake into a future revision of your code.. to automatically determine if an entity is subclassed and build a query appropriately.

        public class UserProfileRepository: GenericRepository, IUserProfileRepository
        public override IQueryable GetQuery()
        var entityName = GetEntityName();
        return ((IObjectContextAdapter)DbContext).ObjectContext.CreateQuery(entityName).OfType();

  62. hi guys,

    anyone have sample implementation of MVC using this pattern?


  63. hi huyrua,

    do you have any sample of MVC implementation?


  64. Thank you for this excellent code. I have been able to take this and use it as a reference in my MVVM application saving me a ton of work.

    I do have a question about Database First implementation of a repository. I have a EDMX file (and associated files) that I can reference using your code as follows:

    _employeeRepository = new GenericRepository(new SidekickEntities());

    where SidekickEntities is the reference to my EDMX in App.Config

    My concern is that implementing the GenericRepository like this will not properly register something, although I am not sure what as I am new to EF.

    • My experience is that if the database is rather small (less than 30 tables or so) that would be better if we use code first development with POCOs since it is clean and clear. For a big database with hundred of tables, you will not want to write hundred of POCOs and mapping code that will consume quite a lot of time.

      Either way, that’s fine if you prefer edmx, which is database first development, to POCOs regardless of the database is small or big. You don’t need to write any mapping code and registration. Just pass the edmx to the repository and you are all set.

  65. I should have mentioned that I am using the Lab.GenericRepository so that I can simply pass in the DbContext from the EDMX.

  66. Hi Huyrua,

    Question for you that you may find interesting. We have an application using this framework as a base, a truly excellent base, as many have said.

    The situation is that all has been going flawlessly – as long as it is running on a single server. However, when we promote it to SDLC environments which are multi-server (i.e. load balanced pair, or higher, such as a farm), eventually we will encounter the following exception messages in the log:

    -Message: A DbContext storage mechanism has already been configured for this application.
    -Message: An item with the same key has already been added.

    These messages are pertaining to the setup of certain static variables, namely: storage, and the context builder dictionary. Clearly, these are supposed to be initialized once and only once, safeguarded in DbContextInitializer by the “is initialized” flag. So, what seems to be happening is that “somehow” the flag is getting bypassed and the static assets are being reinitialized and therefore throwing the exceptions.

    We are noticing this happening generally under the following conditions:

    -During automated deployment using a third-party tool, even though the app pool is being recycled and the app domain (site) is being stopped and started
    -After the app has been running “for some time” (indeterminate) and the app pool recycles

    Any thoughts on this or anything that you might be able to suggest in this scenario?

    Thank you, and happy holidays!


  67. Allen,

    Thanks for letting me know the issue. Actually I am not quite sure what is the root cause of this since I have never deployed the framework on the load-balancing or webfarm environment.

    From your observation, I suspect that is threading problem when storing/initializing the DbContext. Since I do not have an environment to reproduce that problem and try to fix it, as well you understand the framework deep enough, can you do me a favor by debugging and fixing that issue as well tell me, and other readers, your solution? That’s would be great help to make the framework more robust.


    • Hi Huyrua, Happy New Year and thanks for the reply. I am continuing my investigation, and you’ll be glad to know that early indicators may actually be pointing to a configuration problem on the servers themselves rather than with the framework code.

      When it gets down to it, it doesn’t seem to make sense that the application instances on totally distinct (if load balanced) servers can have bad threading interactions on the same DbContext – because they aren’t the same DbContext! (I believe this is a distinction between “web farm” vs. “web garden”.)

      In any case, I’ll update you when the case is closed one way or another. Thanks again!


  68. A great job, congratulations.

    I’m using it in a simple legacy Winforms application and it works, but I have a little problem with binding the collections returned by the generic repository to a grid control.
    In order to reflect changes done in the grid control in the repository entities (when adding or deleting), I need to work with observable collections (BindingList) and not with IList collections, but all your methods resturns IEnumerable collections.

    When I use EF 4.1 directly, without your generic repository, I use the DbSet local property to get an ObservableCollection (for example _context.Categories.Local.ToBindingList())

    Now with your generic repository, I don’t know how to implement it to have a GetAll method returning an ObservableCollection.

    Any ideas?

    Thanks for your great work!

    Alex Bibiano

    • I think you might need to do one step further: convert IList to ObservableCollection.

      • Thanks for your replay.

        Do you mean I have to create a new ObservableColleetion with the ILIst returned by the GetAll method? Somethink like this:

        ObservableCollection customers = new ObservableCollection(_repository.GetAll().ToList());

        If yes, how can I detect new items added or removed to add or remove them manualy in the repository? I have tried to add items directly to the observable collection but changes are not reflected in the repository.

        Alex B

      • I have investigate a little more. Do you tink it’s a good idea to do somethink like this

        public void CreateAccountList()
        _accountTypes = new ObservableCollection(_repository.GetAll().ToList());
        _accountTypes.CollectionChanged += CollectionChanged;

        var a1 = new AccountType { Name = “Bank2” };
        var a2 = new AccountType { Name = “Cash2” };
        int count = _repository.Count();
        Assert.AreEqual(1, count);

        void CollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
        switch (notifyCollectionChangedEventArgs.Action)
        case NotifyCollectionChangedAction.Add:
        foreach (var accountType in notifyCollectionChangedEventArgs.NewItems)

        case NotifyCollectionChangedAction.Remove:
        foreach (var accountType in notifyCollectionChangedEventArgs.OldItems)

        or is there an generic way of doing it?

      • Sorry for late response, been busy these days.

        I dont have a strong opinion on your implementation. From the repository perspective, it should not concern the collection changed events but the CRUD operations, so I think it’s safe to say the repository contract (some to return the IList instead of ObservableCollection) is good enough.

        Your investigation seems solve the problem, but if I am allowed to say, it’s not common (or it’s an old way) that the UI tightly couples with the data access code, you should consider applying some UI design patterns like MVP or MVVM. Just my 2 cents.

      • I have follow your suggestion and implemented a MVP (Supervising Controller) pattern on my simple Winform application. This resolves my problems with Observable collection, … and the code is cleaner. Thanks for your comments.

        I have another question regarding your repository implementation. Whats the best method to discard/undo changes?

        If I load for example a list of person with GetAll and delete and modify some items in the repository and want to discart this changes before calling the UoW save method, whats the best approach to do it?

        I know I can create a new repository and discard the old one, but I’m not sure this is the correct solution?

      • If you want to discard, don’t call the UoW.SaveChanges()

        If you want to support undo/redo, you will need a solution for it, and it’s out of scope of the repository.

  69. Have you considered making a NuGet package for your library? I’m using the GenericRepository frequently, and it would be nice to have it available there.

  70. could you please add a sample to how can I create a many to many query

    Thanks in advance

  71. sorry But I was’nt able to find any , I downloaded the code. could you point me please to the class that have that sample , sorry for the inconvenience

    • It’s under Infrastructure.Tests\Data\Repository\*Test.cs classes or Infrastructure.Tests\Data\Lab\*.Test.cs

      • Thanks a lot, another question, how can I acomplish this

        SELECT * FROM Authors a LEFT JOIN Books b ON a.UserId=b.UserId
        WHERE UserName LIKE ‘ro%’ OR BookName LIKE ‘the %’


        select table1.column, table2.column
        from table1 inner join table2.id = table1.id

        Thanks a lot

  72. I got how to acomplish my first question

    return GetQuery(new Specification(p => p.FirstName.StartsWith(firstname)).And(new Specification(p => p.LastName.StartsWith(lastname))))

  73. Hello,

    I am having trouble deleting in a one to many relashipship , I receive this error

    The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

    I think this is happening because EF wont just automatically delete the an entity from the database just because it has been removed from the collection in my class.

    could somebody advise, how to acomplish this using this framework.

    Thanks in advance

  74. Nice post. Thanks a ton. i am trying use your repository pattern for my implementation , but facing some issues on the update sceanorios. I have exposed the POCO entities to WCF and when i am trying to update a combination of Parent and related entieis. Only the parent entity is gets updated but child entity is not updated.

    I am trying some thing like … A Customer has one or more Customer Address entities. In my client , I have added a new customer Adress , deleted an existing customer Address, and updated an existing Customer Address and modified some thing in Customer Object iteslf. Now, i want to update these changes at one shot.

    Currently, it’s updating only the customer and ignoring the rest.

    I was under impression that, with EF 4.1 the change tracking capablity has been improved and we can acheive this with out STE (self tracking entities). My assumption is correct?
    Can it possible with DBContext? Let me know.

  75. Hello,

    I have this query created

    return GetQuery(new Specification(p => p.FirstName.StartsWith(firstname))
    .And(new Specification(p => p.LastName.StartsWith(lastname)))).Include(“ZipCode”)

    I am using the include to get the zipcodes as part of the same query , but I have noticed watching the sql server profiler that lazyLoading is still active and not just the query with physicians and zipcodes is created but also more queries that return zipcodes.

    is there a way to disbable LazyLoading in some cases neccesary.

    Thanks in advance

  76. It has been a while, hope you are still following this. I’m experimenting a few things:

    – Use the framework in a WCF service with net.tcp where httpcontext is not available
    – Create XyzDbContext where all the DbSet and relational mapping sit together rather than scattered across all entity classes (I know this seems a step backward as you originally documented).

    So if I change your code to GenericRepository(IDbContext context), then use StructureMap to config IDbContext use XyzDbContect and IRepository use GenericRepository, etc., will that work with the rest of your framework without major changes? Does that mean I can get away with WebObjectContextStorage and ObjectContextBuilder?


    • For the contect of WCF, I have been doing the same without any ObjectContext/DbContext context storage. Here is the sample code for your reference, note that I use DB first development by generating a XEntities from X database (here X is database name and XEntities is just my own convention):

      1) Setup IoC container at WCF bootstrapper, here I use Castle Windsor:

      // register db context which is XEntities instance to the container, also name it “myXEntities”

      // register repository

      As you can see, I register repository with the IoC container as well specify the constructor parameter named “dbContext” will be injected with an instance named “myXEntities” in the cotnainer.

      2) Use the repository in WCF code:

      public class SomeRequestHandler : IRequestHandler
      private IRepository _repository;

      // SomeRequestHandler needs to be injected to IoC container too to make dependency injection happens
      public SomeRequestHandler(IRepository repository)
      _repository = repository;

      public SomeResponse Handle(SomeRequest request)
      // use the repositoty


      In short, I think you’re doing the right thing or at least you’re doing the same as me, and I haven’t found any problem with this so far.

      Hope this help.

  77. Is there any possibility to use 2 (or more) databases at the same time.

    My project (winforms) should be plugin-enabled. That means that a user should be able to install at runtime a new plugin (mdi forms) which should have its own database (sql ce). How can I attach the new database/s to the context? The new database/s are only known at runtime. It would be ok if only the plugin classes can access their own database.

    Any ideas?

    • Sure you can, since GenericRepository constructor accepts a connection string name, so you can create many instances of GenericRepository with different connection string names, each will access to a specific database.

  78. Thanks for the reply. Now I finally see how your framework actually build the context. Amazing stuff.

    Now on the other front, I’m also experimenting with a WcfObjectContextStorage. I have a question regarding the existing WebObjectContextStorage. This is what I have now

    public override void Init() {
    _storage = new WebObjectContextStorage(this);}

    void Application_BeginRequest(object sender, EventArgs e){
    .InitializeObjectContextOnce(() =>{
    { Server.MapPath(“~/bin/Business.dll”) });});}

    I think I did this from reading one of your replies. Is this correct? Should ObjectContextInitializer run on every request?

    One problem I run into is when creating a WcfObjectContext, OperationContext isn’t available until BeginRequest. But I couldn’t figure out the significance of moving new WcfObjectConextStorage(this) into Application_BeginRequest.

    • Yes, ObjectContextInitializer will run on every web request, but the method InitializeObjectContextOnce ensures that the storage will be initialized once.

      If you’re using Repository with WCF, as my reply, you don’t need a WcfObjectContextStorage.

  79. Hi,

    Is there a way to make a specification depending on the latest date? I am trying to make a specification wherein it takes the latest instance of an entity with the latest date. something along the lines of (x => x.Statement.Date IsLatest)?

    • You might want to try Max method with Linq. Another approach is ordering (descending) then get the first item:

      …OrderByDescending(x => x.Statement.Date).FirstOrderFault();

  80. I updated the GenericRepository with an IDbContext constructor and works well with StructureMap injection, etc. But the whole process lead me on a different path of thinking.

    After some further reading on Dependency Injection, IDbContext with DbContext, FakeDbContext, FakeDbset, etc., it seems using DbContext this way can accomplish almost everything a generic repository can do, except technical purity of no EF dependency from service layer. But in return, the code is simpler and still testable.

    Did I miss the point? Thanks.

    • If you’re applying DDD in your work then you will understand why we implement a repository (this framework is just a reference implementation of Repository). I would try to avoid to explain why we need it because it was quite popular now. However, you’re right that using a Repository is readable as well loosely couple with ORM framework. Also, from developer point of view, they do not need to have much knowledge of EF.

      • Thanks for explaining. I was referring to a few posts claiming DbContext is the UoW and DbSet are the repositories, so one shouldn’t need a generic repository on top of it. Plus DbContext/DbSet are also mock/unit test-able. They argue that switching underlying data access is rare in non-commercial software development, so dependency on EF is OK, if it can save a few lines of code.

        I have always been tempted by the convenience of using DbContext directly and tried several times moving in that direction. But once in there, it felt more like writing adhoc inline SQL than anything else. So I just backed out n-th time end of business day yesterday ^_^ Although I still can’t really tell the difference between a generic repository returning IQueryable vs DbContext/DbSet, seems just different syntax.

        Sorry, these questions are probably too amateurish, hope you don’t mind.

      • I think I know the correct answer now: it depends ^_^

  81. Hi huyrua,
    Excellent work here. Could you explain how we can use Attach in your implementation? I couldn’t find an easy to to attach an existing object in entity poco?

    • var foo = new Foo { Id = [some id], … }; // [some id] maybe the one from request parameter

      // attach the entity to repository (context)

  82. Hi huyrua,

    I really like this and it works well. I’ve made some modifications especially in thw UoW to handle concurrency issues since the DbContextManager/ Storage maintains a long running context – something everyone advises against, however I like your explanation for maintaining the level 1 cache.

    Can I ask a question please? I see in the above comment (somewhere) that someone has mentioned the CurrentFor is not threadsafe. This is true. I have multiple threads performing actions through the repositories. However I’m not sure how to go about making it threadsafe. I hope this isn’t too much of a silly question and forgive me for being dumb here.


  83. Hi huyrua,
    Thanks for usefull libraries,

    How Can I disable default pluralization service in generic repository?
    Is there any way without changing your code ?
    I just download and compiled as dll and using so

  84. Hi Huyrua,
    I was working on a solution where DbSet names did not obey pluralization rules. So, the GetEntityName method could not return thr correct DbSet name. I have changed the code to the following and did not use pluralization servies at all. Thought you might want to add this to source:
    string entitySetName = ((IObjectContextAdapter)DbContext).ObjectContext.MetadataWorkspace
    .GetEntityContainer(((IObjectContextAdapter)DbContext).ObjectContext.DefaultContainerName, DataSpace.CSpace)
    .BaseEntitySets.Where(bes => bes.ElementType.Name == typeof(TEntity).Name).First().Name;
    return string.Format(“{0}.{1}”, ((IObjectContextAdapter)DbContext).ObjectContext.DefaultContainerName, entitySetName);

  85. One other thing to note is that, It’d be excellent to have a famous IoC library used in your solution (Maybe let the user decide to use your custom dbcontextmanager or the IoC library) to manage creation/initialization and scope of DbContext. Maybe Castle Windsor?

    • Thanks for your suggestion. I know there should be a sample project to show how to use the framework with an IoC container. However, I don’t have any good idea on which sample is good enough to build, so I leave it to the reader 😀

  86. Thanks for your code!
    If I want to use Table per Hierarchy (TPH) like this (class News : Content () {…})
    var news = repository.GetAll(); I have error
    Thaen I tried different way like this:
    var news = repository.GetAll().OfType();
    as I understood first we get all Content entities and then localy find News?
    What you can recomend to work with TPH to do not take large query?

  87. I have been able to implement your code in a WPF application but am looking for a way to check if a change on the repository is pending. I have a window of company info and if the user makes a change and then tries to close the window without saving the changes I would like to notify the user that the changes have not been saved. Any suggestions?

    • IMHO, repository should not be involved in tracking/detecting changes in the Model. However, If you’re applying Model-View-ViewModel, this would be easy because the ViewModel implements INotifyPropertyChanged interface. This way, the ViewModel, e.g. CompanyInfoViewModel in your case, would know which property has changed and display a dialog asking for saving. This I think is a simplest solution for this scenario.

  88. Hi Huyrua,

    I’m using your code for a WF-application and I try to switch it to EF 4.3, because I want to use the new migrations features for updating the database during development.

    When I try to enable migrations I get the following message:
    “No classes deriving from DbContext found in the current project.
    Edit the generated Configuration class to specify the context to enable migrations for.”

    Unfortunately the configuration class needs a DbContext:

    internal sealed class Configuration : DbMigrationsConfiguration

    I know that I can convert the ObjectContext into a DbContext, but I don’t know how I can pass it into this configuration class.

    Is there any possibility?

    • I just saw, that I could use the Lab-version of your code. There I have the DbContext. I try to change my app and than switch to EF 4.3 again.

  89. I was wondering if anyone has a Generic Repository like this, targeting .Net 3.5 (EF v1). I am trying to use EF with Sharepoint 2010, which will only take .Net 3.5. Several methods such as _context.CreateObjectSet do not have a counterpart. Or a way to extend the .Net 3.5 System.Data.Objects to include them. I had thought about WCF service calls to a .Net 4.0 Client, but I do not think that can be hosted on the Sharepoint server either.

    Any guidance would be appreciated.


  90. Just curious if you have tested your code against the new release of EF 5.x? Will you be releasing an updated version of your package for the new EF5.x?

  1. Pingback: traiteur rabat

%d bloggers like this: