Entity Framework’s Code First is one of my favorite tools, but in my experience it is somewhat uncommon to build a database from scratch. More often you are accessing and editing data in an existing database, or modifying its schema. Thankfully, Entity Framework 6.1 introduced “reverse code first”, which is more officially known as “Code First From Database”. This pattern allows you to choose an existing database, and Entity Framework will generate the appropriate entities and DbContext classes for it. This can also be a great option if you are a fan of code first syntax but still prefer to design your databases through SQL or Management Studio.
When you first start using Code First From Database, however, it won’t be long until you run into a problem. The framework generates correct entity classes for you based on your database tables, but what happens when you want to add additional meta data to these classes? Maybe you want to enforce certain model validation rules that don’t actually exist in the database. How do we add this meta data? Sure, you can add them directly to the classes Entity Framework generates, but if the database changes and you need to regenerate the classes, you’ll loose these updates. There must be a better way!