Protecting .NET applications that use Entity Framework
Published on November 27, 2018 by John Brawner
Entity Framework is an object-relational mapping (ORM) framework used in Xamarin, WPF, ASP.NET and many other types of .NET applications. It greatly simplifies the code that a developer typically needs to write for database access and querying.
Entity Framework pairs the names of database tables to the names of model types in source code that are used to generate the tables. These names must stay consistent for the application to function properly. This means that when performing renaming obfuscation on these sections of code, we must exclude the model types from renaming.
Please consider this sample which uses EF Core 2.1:
There is a Person model, whose properties map to the columns of the database:
There is a PersonContext object of type DbContext that handles reading and writing to the (SQLite, in this case) database:
The following Dotfuscator rename rules are required in order to ensure our application runs properly:
1. We must first exclude the Person model to ensure that its properties match the columns of the Persons table. Please note that by excluding Person, the property metadata is also excluded. We don’t need to manually exclude Name and PersonId
2. Within PersonContext, we must exclude the Persons property of type DbSet. The Entity Framework code expects this to match the Persons table as generated by the Database Migrations.
If we did not have these exclusions in place, we might experience a runtime exception from the database access code like the following:
Entity Framework has evolved over the years, but the key idea is the same when applying renaming obfuscation: the database table and column names must match the corresponding class and property names of the models in code.
You can download the full example here.
If you have any feedback on this topic, or other topics you would like us to discuss in the Support Corner, please feel free to contact us at email@example.com.