Entity Framework Code-First

 Oct 02, 2015

In today’s blog I will review how to use the Code-First approach with Entity Framework.

Entity Framework (EF) is the preferred technology to create a Data Access Layer (DAL) to MVC applications. There are 3 general approaches to create the DAL with EF: Model-First, Database-First and Code-First.

In the Model-First approach you generate the data model by using the Entity Designer and then you generate the entity classes and a script to create the database if you don’t have the database yet. The data model is saved as an xml file with the extension .edmx. This file can be edited directly or preferably with the designer.

In the Database-First approach you always start with an existing database and a wizard will generate a data model for you and save it as an .edmx file. You can later open the .edmx file with the Entity Designer tool and make any necessary changes.

With the Code-First approach there is no .edmx file like the previous 2 approaches. You don’t use any graphical tool, just plain entity classes that will be somehow connected to an existing database or to a database that will be created as part of the process. We will dig deeper into the details of how to implement the Code-First approach in a MVC application.

You start by creating a set of entity classes to represent your domain objects. For example you create classes like Customer, Product, Order, Employee, etc.

public class Customer { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } … }

Note that there is nothing in the code that connects this plain C# class with the EF. We rely on the convention that a property called Id will be mapped to a primary key also called Id in the table that will be the backend to this entity class in the database. We could have chosen this property to be called CustomerId. Anything else would require custom attributes or the use of the Fluent API that we will address in a subsequent post.

Now you need to create a class that inherits from DbContext that will be the glue between your domain entity classes and the corresponding tables in the database. You can add the reference to EF by using a Nuget package. Only after that you would be able to use the DbContext class.

public class SalesContext : DbContext { … }

Now inside SalesContext let’s first add a constructor that will tell EF what the connection string to access the database is.

public SalesContext(string connectionString) : base(connectionString) { }

If you skip the creation of this constructor EF would look for a connection string with the same name as the context class, in our case SalesContext.

Now for each one of the entity classes in the domain you add a corresponding property that returns a DbSet. For example,

public DbSet Customers {get; set;} public DbSet Products {get; set;} public DbSet Orders {get; set;} Finally in the action methods of your MVC controllers you can use the SalesContext class to implement CRUD (Create, Read, Update, Delete) operations for your entities. For example, using( SalesContext context = new SalesContext(“SalesDB”) { Customer cust = new Customer(); cust.FirstName = “John”; cust.LastName = “Doe”; context.Customers.Add(cust); context.SaveChanges(); }

If you want to update an entity you use the method Find of the Customers collection passing the Id of the Customer and then you modify the required properties and finish by calling SaveChanges as above. To delete you use the Delete method.

You can see that once you have the context instance SalesContext it is straight forward to manipulate the entities. You don’t have to worry about writing lower level ADO.NET code to operate directly on the database tables. In the end your EF code is translated into ADO.NET calls, but that is completely transparent for you.

To learn more about creating MVC applications using EF we recommend New Horizons' 20486 - Developing ASP.NET MVC 4 Web Applications training course.

How do your Excel skills stack up?   

Test Now  

About the Author:

Newton Godoy  

With over 17 years of in-class training experience and over 16 years of industry experience, Newton offers students a wealth of real-world technical knowledge and expertise in the areas of .NET application development, SQL Server and SharePoint Server. After spending several years lecturing as a professor, Newton found his true calling and began his career as a MCT. He worked as a technical trainer for some of Brazil's and Australia’s largest corporate training organisations before finally finding a home with New Horizons where he is now one of our top trainers. Newton brings a thorough mentoring capability to the classroom where he can advise on technical issues and challenges often beyond the scope of the course curriculum. His combination of technical knowledge and instructor experience make him one of the most respected instructors within the IT training industry.

Read full bio
top
Back to top