Code First Entity Framework: Building Data Layers in Your C# MVC Applications

code first entity frameworkIf you wrote old C# applications during the Windows and Web form years, you’ll remember using ADO.NET to connect to your database. You built connections, queries, and handled stored procedure code and parameters in the database. Now, with ADO.NET and Entity Framework, you can eliminate much of the hassle needed to work with data and databases in C#. Entity Framework (EF) and LINQ work together to allow you to create a data layer for your applications.

Learn how to work with Entity Framework, MVC and C# at Udemy.com.

Before you get started with Entity Framework, it helps to know a little about MVC, which is probably the framework you’ll use when you create your application.

What is MVC?

The model-view-controller (MVC) framework is a lot different than old web forms. With MVC, your applications are separated into compartments. You no longer need to keep track of page state such as loading and unloading. Instead, MVC takes care of this process and just lets you design business logic and data design.

The model is what contains your data. Models are usually created in ViewModels. ViewModels are classes that have some data logic that map to your database tables. Entity Framework is more like a one-to-one relationship between a class and a database table. With a ViewModel, you customize the way you want your model to look. For instance, you could have a CustomerOrderViewModel that contains some data logic with both your customer and order tables.

The view is the visual part of your application. The view contains all the HTML elements for your users. Your view is given a data model (or ViewModel) that it can use to display data. In a view, you usually use a technology called “Razor.” Razor contains a number of HTML helper classes that turn multiple C# lines of code into one or two lines. The result is much shorter code, easier to read and better performance. You can also write your own helper classes for your views.

Learn more about the MVC framework and C# at Udemy.com.

Finally, the controller is the class object that contains all of your business logic. The controller passes the model (or ViewModel) to your view. The controller maps to the view based on its name. When you create an “Orders” view, you then create an “Orders” controller. The MVC framework knows to map the two together, so you don’t need to specifically establish a connection between the two objects. You can create ViewModels separately and call the ViewModel class from the controller. You then manipulate the data and then send the data model to your view.

Code First Classes and Your Database

Code first differs from older SQL querying and table manipulation. If you coded web forms, remember you needed to create your stored procedure in the SQL database, set up the parameters and procedure name in your code, call the database and then handle the result set. The data result set was clunky, and you had to code for empty data sets and whenever you ran out of records. You also needed to code for separate insert and delete statements.

With code first, your database tables are represented as classes. For instance, you might have a customer table in your database. The following code is an example of a code first Entity Framework class:

using System;

using System.Collections.Generic;

publicpartialclassCustomer

{

public User()

{

this.Order = newHashSet<Order>();

}

publicint CustomerId { get; set; }

publicstring Username { get; set; }

publicstring FirstName { get; set; }

publicstring LastName { get; set; }

publicvirtualICollection< Order > Orders { get; set; }

}

}

The first two “using” statements are similar to “include” statements. These two lines of code include libraries into your code. The “partial class” statement defines a class name. In this case, the class name is “Customer.” With Entity Framework and code first, you know that this identifies a table named “Customer” in your database.

Next, the “User” constructor statement is defined. A constructor is a part of your class that has no return type but it is always the same name as the class. In the case of an Entity Framework code first class, the statement in this constructor initializes a foreign key. Foreign keys link your tables together. In this case, it’s a record set in the “Order” table. The statement grabs all records in the foreign key link in the table and returns an “ICollection” data type. This data type is used often in your table class models when you need to return linked table rows. Notice the collection is defined in the last class statement. The “Orders” class property contains the list of orders for a specific customer Id.

The final lines of code are the class’ properties. In this customer class, there is the CustomerId, the Username, the FirstName and the LastName columns. The data types are “int” for integer and string.

After you define these classes, you can use them to query your database without any SQL or cumbersome code. The following code is an example of using LINQ with the above customer and order classes:

var customer = (from c in db.Customer join o in db.Order on c.CustomerId equals o.CustomerId where c.CustomerId = 5).FirstOrDefault();

The above line of code grabs a customer with the Id of 5.  The returned data set is in a “Customer” class, which is also mapped to your customer database. The result is that you can return data to a class and use this class to read and manipulate your data. Instead of looping through a data set and identifying rows and columns, you just have a collection of customers. The collection is enumerated, so you can loop through each customer record using the foreach loop structure.

This is just a small glimpse into the Entity Framework and building class structures for your tables. It’s a little difficult to learn when you’re first starting out, but once you work with EF for a while, you’ll find it’s much more convenient than working with older technology.

Learn more about MVC and EF at Udemy.com.