Using the Code First Approach with Entity Framework

Using Entity Framework, we can take a Code First Approach developing the data models and allow EF to translate the model classes into database tables. The properties of classes become the attributes of the tables. Defining an ID for a class will result in a primary key and referencing that ID from another class will create a foreign key relationship. The first step is to import EF to the application.

Import Entity Framwork

 

It will be useful to create Controllers and Views from the Models. With a DbContext Model in place: run build, then enable migrations from the PM Console, add an initial migration and run update-database. At this point, EF creates the database in LocalDb. See the initial create file in the Migrations folder for the operations run on update. Repeat with add-migration [name] whenever the models change and update-database.

Connect LocalDb

Further control can be gained by defining the connection string in the Web.config file and modify the Configuration.cs. For example, seeding the database with preliminary data. The connection string is also the place to attach the DB if you want to see it in the App_Data folder. It will appear after building and executing the app.

App Data mdf