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 NowNext up:
- The awesomeness that is AngularJS - Part 1
- What Customers Want
- Deleting an undelete-able site collection
- Non-Breaking Spaces & Non-Breaking Hyphens in Word
- Creating a simple Website and User Interface with MVC - Part 1
- Welcome to the new Edge
- Courage? …I’m feeling quietly confident
- Save time by using your Document Stencil
- Creating a simple Website and User Interface with MVC - Part 2
- Create Scenarios in Excel using cell names
Previously
- Introduction to Office 365 Video
- The Aussie Meat Pie of Managing Teams
- Cascaded Dropdowns in Nintex Forms
- Create a Chart Template in Excel
- Setting up your models in MVC
- No need for meeting notes anymore!
- “If you can’t measure it…”
- The best features in Office 2016!
- Use a slicer to make better business decisions
- What's a JavaScript Closure?