EfGen.exe – a command line tool for automatic generation of Entity Framework DLL

Download

EfGen.exe is a command line tool to automate the EDM Wizard in Visual Studio.

While working with Entity Framework, I consider it a best practice to create a stand-alone dll that contains all the code Entity Framework (EF) generates to communicate with the database. I would use the EDM Wizard in Visual Studio to point EF to a database, let it generate the code, and then compile it into a dll. This dll would then be referenced by my project(s) that would like to use EF to communicate with my database. I wanted a tool to automate this process of generating the EF dll, and this is where EfGen comes in. You give it a connection string, and it outputs a dll named efmodel.dll by default. You can then reference this dll in your projects, and create an instance of following class to query the database:

    // use the --context option (see usage) to change the name of the class
    // use the --namespace option (see usage) to change the namespace
var db = new EFModel.EFContext(); // inherits DbContext

Comparison with edmgen.exe:

  • edmgen does not allow you to select which of the following database objects to include in the EF model: tables, views, functions (aka stored procedures). By default, efgen is designed to include all of the tables, views, and stored procedures in the generated model. However, you can customize it to exclude tables, views, stored procedures by using the --noTables, --noViews, --noFunc flags respectively.
  • The latest version of Visual Studio (2012 at time of this writing) and EF (EF 5.0) generates code based on T4 templates. Older versions used some kind of custom tool. One of the differences between the code generated by the two methods is that the latest method generates a class that inherits from DbContext whereas the older method generated a class that inherited ObjectContext. Edmgen uses the old method, while EfGen uses the new method
  • edmgen does not output a dll

Another point worth mentioning is that if you are using the EDM Wizard, it generates a class like below:

        public partial class MyEntities : DbContext
    {
        public MyEntities()
            : base("name=MyEntities")
        {
        }
        

and adds a ConnectionString named MyEntities to the config file (app.config or web.config). This is very annoying to me for several reasons:

  • If I am going to compile the EF code into a separate stand-alone dll, then the connection string has to be copied to the config file of the executable assembly or web application. If there are 10 projects that are going to use EF to communicate with the db, this connection string has to be copied 10 times.
  • What if I don’t want to pass the connection string from the config file? You are out-of-luck. You will have to extend the partial class generated by EF, and add a constructor
    that takes input the connection string.

EfGen has been designed so that it exposes a parameterless and a parameterized constructor:

            public partial class EFContext : DbContext
    {
        public EFContext()
        public EFContext(string nameOrConnectionString)
        

There is no connection string generated in the config file, and no connection string to copy from one config file to another. When you run efgen, you supply it a connection string,
and the parameterless constructor uses that same connection string to connect to the database. If you want to override the connection string, you can use the other constructor, but make sure it contains the CSDL, SSDL, MSL metadata needed by EF to query the database. Refer msdn for details.

Using the tool

  1. Install Entity Framework, if you don’t have it already. See http://msdn.microsoft.com/en-us/data/ee712906
  2. Download zipped files containing precompiled binaries, and unzip.
  3. Note down the folder where EntityFramework.dll is located. This folder needs to be input to efgen using the --efPath switch. I installed EntityFramework.dll in my GAC and it got installed under C:\Windows\Microsoft.NET\assembly\GAC_MSIL\EntityFramework\v4.0_5.0.0.0__b77a5c561934e089. The --efPath variable has been set to this value by default. You will most likely need to override it, with your own location where EntityFramework.dll is located.
  4. Run the tool like this:
                        EfGen -c "data source=machine-name;initial catalog=database-name;integrated security=True;MultipleActiveResultSets=True" --noViews --noFunc
                    

    In above, we are only including the database tables in our model. We are not including the views and stored procedures (--noViews and --noFunc respectively). This should generate a file efmodel.dll that is ready to be referenced in your C# projects that want to use EF to query the database. Use the -o option to change the name of the output dll.

  5. Add reference to efmodel.dll, and create an instance of EFContext to query the database:
                    // use the --context option to change the name of the class
        // use the --namespace option to change the namespace
    var db = new EFModel.EFContext(); // inherits DbContext
                    

Use the --stages option if you just want to generate .cs files and not want to compile them into a DLL.

Here is complete usage of the tool:

Usage: EfGen [<options>]
 e.g., EfGen -c "data source=machine-name;initial catalog=database-name;integrated security=True;MultipleActiveResultSets=True" --noViews --noFunc
 where:
  -c, --connectionString    Required. Connection String

  -o, --out                 (Default: EfModel.dll) Name of output dll

  -n, --namespace           (Default: EFModel) Namespace

  -p, --provider            (Default: System.Data.SqlClient) The provider used
                            to connect to the data store

  --context                 (Default: EFContext) Name of class that inherits
                            from DbContext. Also known as the container class

  --noTables                Exclude database tables from being included in the
                            entity framework model

  --noViews                 Exclude database views from being included in the
                            entity framework model

  --noFunc                  Exclude database functions from being included in
                            the entity framework model

  --nofk                    Do not generate foreign key properties in the
                            entity framework model

  --noXml                   Suppress generation of XML Documentation file

  --stages                  (Default: 3) An integer between 1 and 3; if stage =
                            1, then only .edmx file is generated; if stage = 2,
                            then .edmx file + .cs files are generated; if stage
                            = 3, then .edmx, .cs files are generated, and .cs
                            files are compiled into a dll

  --incFolder               (Default: $(ProgramFiles)\Microsoft Visual Studio
                            11.0\Common7\IDE\Extensions\Microsoft\Entity
                            Framework Tools\Templates\Includes) Folder where
                            EF.Utility.CS.ttinclude is located

  --t4vs                    (Default: $(ProgramFiles)\Microsoft Visual Studio
                            11.0\Common7\IDE\Microsoft.Data.Entity.Design.dll)
                            T4VSHost for CleanupBehavior; see
                            http://bit.ly/YtRl8Y

  --efPath                  (Default:
                            $(windir)\Microsoft.Net\assembly\GAC_MSIL\EntityFram

                            ework\v4.0_5.0.0.0__b77a5c561934e089) Path where
                            EntityFramework.dll is located

  --version                 Assembly version of the generated dll e.g.,
                            "1.2.3.4"

  --help                    Display this help screen.
This entry was posted in Software. Bookmark the permalink.

18 Responses to EfGen.exe – a command line tool for automatic generation of Entity Framework DLL

  1. stepan's avatar stepan says:

    Is there source code available for this tool ?

    • jan.slavsky@gmai.com's avatar jan.slavsky@gmai.com says:

      Look good but it is requesting dll from VS 2012 – unfortunatelly we have only 2010 and 2013 – is there a source code so we can use it with our versions of VS?

      Error: Could not load file or assembly ‘Microsoft.VisualStudio.TextTemplating.11
      .0, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ or one o
      f its dependencies. The system cannot find the file specified.

    • Siddharth Jain's avatar fd97207 says:

      sorry no source code.

  2. VP's avatar VP says:

    I am getting following error
    warning 6013: The table/view ‘Schema.dbo.Table’ does not have a primary key defined and no valid primary key could be inferred. This table/view has been excluded.

    It will be great, If you help me to overcome this issue!

    • Siddharth Jain's avatar fd97207 says:

      this is just a warning. the problem is that you have no PK (primary key) defined for Schema.dbo.Table. please define a PK for this table to fix the warning.

  3. aleifsson's avatar aleifsson says:

    “Could not find any .tt files under %directory%”. Isn’t the EfGen suppose to generate the .tt as well?

  4. johnye2e's avatar johnye2e says:

    The download is not available anymore. Can you please update the download link?

  5. Srdjan's avatar Srdjan says:

    when I try to generate dll I get following message:
    “Could not find any .tt files under C:\Windows\system32”

  6. Srdjan's avatar Srdjan says:

    I fixed this issue. It generates files in current folder of cmd. One more question, is it possible to override name of .edmx file?

  7. Luca's avatar Luca says:

    not works for me, I get:
    Could not load file or assembly ‘TextTransform, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ or one of its dependencies. The system cannot find the file specified.
    at EfGen.CodeGenerator.Run(Options options, IList`1& warnings, IList`1& errors)
    at EfGen.Program.Main(String[] args)

    I use vs 2017.

    The project is stil active? There is a way to collaborate to the project?

Leave a reply to jan.slavsky@gmai.com Cancel reply