Search code examples
entity-frameworkentity-framework-5ef-model-first

Disable the default constructor on a Database-First workflow


How can I prevent the use of the parameterless constructor of the generated DbContext?

var dcx = new DataEntities();

The default constructor is generated by the T4 template, and I thus cannot override it in a partial class. I would prefer it not compile, but a runtime error would also be good.


Solution

  • You can modify the template to provide the constructor you want.

    • Open the *.Context.tt file
    • Go to line ~59
    • Change this code.

      public <#=code.Escape(container)#>()
          : base("name=<#=container.Name#>")
      
    • Into the default constructor you want, for example.

      public <#=code.Escape(container)#>(string nameOrConnectionString)
          : base(nameOrConnectionString)
      
    • Save