Search code examples
c#entity-frameworkc#-4.0pocotexttemplate

How to generate navigation properties with EntityFramework Reverse POCO Generator?


I was previously using the EF Power Tools which included an option to ReverseEngineerCodeFirst, and in the process of switching to EntityFramework Reverse POCO Generator.

Implementation:

        using (var db = new DbContext())
        {
            var user = db.Users
                .Include("MembershipType")
                .FirstOrDefault(u => u.UserName == userName);
            . . .
        }

In using the POCO generator, I now get an error on the .Include(...) line:

'System.Data.Entity.IDbSet' does not contain a definition for 'Include' and no extension method 'Include' accepting a first argument of type 'System.Data.Entity.IDbSet' could be found (are you missing a using directive or an assembly reference?)

In the generated context (and IContext):

    DbSet<User> Users { get; set; } // Users

In the context tt template, I changed instances of IDbSet to DbSet which fixed the issue, but I'm curious as to why, if IDbSet is an interface for DbSet, why doesn't IDbSet work?


Solution

  • The error says it all:

    System.Data.Entity.IDbSet' does not contain a definition for 'Include' and no extension method...

    The interface just doesn't have the method. I'm not sure why these method are not part of the interface. Maybe because IDbSet was introduced to facilitate mocking, and Include is a method that's very hard to mock.

    Instead, you can use one of the the Include extension methods in the namespace System.Data.Entity. These method are defined on IQueryable(<T>), which is an interface that IDbSet implements.

    The same is true for another important method that's not in the IDbSet interface: AsNoTracking. (Also hard to mock - in a sense - because tracking is hard to mock).