Entity Framework- Code First Approach


Entity Framework- Code First Approach

The Entity Framework provides three approaches to creating an entity model, and each one has its pros and cons.

  • Code First
  • Database First
  • Model First

Entity Framework has a modeling workflow referred to as Code First.

  • Code First modeling workflow targets a database that doesn't exist, and Code First will create it.
  • It can also be used if you have an empty database, and then Code First will add new tables to it.
  • Code First allows you to define your model using C# or VB.Net classes.
  • Additional configuration can optionally be performed using attributes on your classes and properties or a fluent API.

Why Code First?

  • Code First is made up of a set of puzzle pieces. First are your domain classes.
  • The domain classes have nothing to do with the Entity Framework, and they're just the items of your business domain.
  • The entity Framework, then, has a context that manages the interaction between those classes and your database.
  • The context is not specific to Code First, and it's an Entity Framework feature.
  • Code First adds a model builder that inspects your classes that the context is managing and then uses a set of rules or conventions to determine how those classes and the relationships describe a model and how that model should map to your database.
  • All of this happens at runtime. You'll never see this model; it's just in memory.
  • Code First also can use that model to create a database if you want to.
  • It can also update the database if the model changes, using Code First Migrations.

Environment Setup

To start working with EF Code First approach, you need the following tools to be installed on your system.

  • Visual Studio 2013 (.net framework 4.5.2) or later version.
  • MS SQL Server 2012 or later.
  • Entity Framework via NuGet Package.

Install EF via NuGet Package

Step 1 − First, create the console application from File → New → Project…

Step 2 − Select Windows from the left pane and Console Application from the template pane.

Step 3 − Enter EFCodeFirstDemo as the name and select OK.

Step 4 − Right-click on your project in the solution explorer and select Manage NuGet Packages…
This will open NuGet Package Manager and search for EntityFramework. This will search for all the packages related to the Entity Framework.

Step 5 − Select EntityFramework and click on Install. Or, from the Tools menu, click NuGet Package Manager and then click Package Manager Console. In the Package Manager Console window, enter the following command: Install-Package EntityFramework.
When the installation is complete, you will see the following message in the output window “Successfully installed 'EntityFramework 6.1.2' to EFCodeFirstDemo”.

3