Brandon Michael Hunter
Brandon Michael Hunter

Reputation: 1221

C# - maintaing interface after updates on ef .edmx file

I'm working on a MVC project where I'm working towards updating the code base so that we can begin using MS Test to test our code base. My approach is use a Repository pattern for our interaction with databases and using Dependency Injection to help develop mock objects in our testing project.

Our MVC project uses a database first approach for updating the .edmx file. We use VS to generate the code when we adding\updating tables and other db objects. When updates are made to the .edmx file, then this updates my project's DBContext class. My DBContext class implements an interface that had I created which stores all of the tables (DBSet<TableName>) that I use in my project.

Every time I update my .edmx file with a new table, VS removes the reference to my interface.

I want to know how can I stop VS from removing my interface reference in my DBContext class. Every time I update my .edmx file VS removes my reference to my interface file and when I run my MS test project I get errors because my DBContext object no longer implements the interface that I created.

Upvotes: 2

Views: 142

Answers (1)

Jonathan Alfaro
Jonathan Alfaro

Reputation: 4376

Option 1::

You can change your T4 Template.

Find your EDMX file. Nested within that file there is a file called NameOfYourModel.Context.tt and inside that file there is a line similar to this one:

<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext

That line of code is the one that generates your Context. So next to DbContext add ", Interface Name" so the end result will be like this:

<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext, IMyInterface

Save the file. Now every time you regenerate the code your Context will have that interface in it's declaration. You can make further modifications to the generated context in this file.

Option 2:

The other option is to create a partial class in a separate file with the same declaration as your Context. And put your custom code inside that file. Partial class files get merged into a single class at compile time. They have to be in the same project and under the same namespace.

For more information on Partial Classes

Upvotes: 1

Related Questions