Disable the default constructor in the Database-First workflow

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

var dcx = new DataEntities(); 

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

+6
source share
2 answers

You can modify the template to provide the desired constructor.

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

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

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

+11
source

You can inherit the DbContext created by the template, define your own constructor, and use the inherited DbContext instead of the one created by the template.

 public class MyModifiedDbContext : TheTemplateGeneratedDbContext { public MyModifiedDbContext() { // define your own constructor } } 

Or make it private to avoid using it, so you get an error at compile time

 public class MyModifiedDbContext : TheTemplateGeneratedDbContext { private MyModifiedDbContext() // ... } 

Use MyModifiedDbContext instead of TheTemplateGeneratedDbContext

+1
source

Source: https://habr.com/ru/post/972944/


All Articles