The Entity Framework data model

Entity Framework, in the words of Microsoft, is as follows:

Entity Framework (EF) is an object-relational mapping technology that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write. Entity Framework is the Microsoft's recommended ORM modeling technology for new .NET applications.

Note

You can find a nice, although basic, introductory video about Entity Framework at https://msdn.microsoft.com/en-us/data/ef.aspx.

As mentioned earlier, the latest version is .NET Core 1.1, and it's still in the adoption phase by the community, so we're using version 6.0 here, which is totally stable and widely tested. In this version, you have three initial choices: starting with an existing database, starting with an empty model, or starting with already existing code.

In the first case, called Database First, a connection is established to the DBMS to read metadata from the server and create a visual model of the selected objects. From that model, a set of classes is generated, which includes a wide range of CRUD and search operations by default.

Similar to this is the behavior of the Model First option, in which you start from scratch, design a model in the graphical editor, and the classes' generations process follows. Optionally, you can generate the real database in the RDBMS depending on the connection string. In either case, you can automatically update your model when the underlying database changes, and the related code will be automatically generated as well. Both database generation and object-layer code generation are highly customizable.

In the third option, Code First, you start from some existing code and a heuristic process takes place in order to infer the corresponding model from that code, the rest of the options being similar to the other two scenarios.

For a deeper approach at Entity Framework, I recommend Mastering Entity Framework, Rahul Rajat Singh, Packt Publishing (https://www.packtpub.com/application-development/mastering-entity-framework).

For the purpose of the next demo, I'm using the Database First approach in order to show the most common operations with Entity Framework but changing the project type to be an ASP.NET MVC application this time, where the code used for data access should be totally independent from the IU that consumes the data.

So, let's create a new ASP.NET application by selecting that option in the available projects. We will be offered several types of project variations depending on the version and project architecture:

The Entity Framework data model

I selected the No Authentication feature in Change Authentication in order to avoid the automatic creation of a database. When clicking on OK, a new project will be generated (using the techniques we saw in previous chapter), and we'll end up with a basic, but functional, project with no data access.

At this point, the Models folder should be empty. So, right-click on that folder, select Add New, and in the Data menu, choose ADO.NET Entity Data Model. I'll name mine AWModel and proceed. At this point, you have to select the type of designer to use, which determines the model's contents. I've selected EF Designer from Database.

Now, it's time to select the connection. The last one used will be presented by default, and the dialog box will generate a connection string in RichTextBox at the bottom. In case AdventureWorks doesn't show up, manually select the connection to be used.

Then, it's time to pick up which tables you want to work with, along with other objects, such as views and stored procedures. All of them will be used to generate the model.

For this demo, I selected one table with a few columns to facilitate code reading, so I opted for HumanResources.Department with just four fields:

The Entity Framework data model

A simple schema should appear in the Design window and its properties, detailed in a bottom window called Mapping Details, which specifies how the original data types and restrictions defined in the database are modeled into the C# language, to be managed by Entity Framework classes.

This is important, since it allows you to specify exactly how you want EF Generators to behave when creating the actual code.

There's another important feature to remember here. More often that not, changes happen in the original database, and that includes column reformatting or changing datatypes, adding (or deleting) tables, changing relations, and so on.

In these cases, the contextual Update Model from Database option comes in handy. The entire model will be reread, and the corresponding changes will be updated, both in the Mapping Details section and the generated code, which will be regenerated:

The Entity Framework data model

Now, we need to understand how to modify code generation. This is done by means of the T4 templates, which are text files with the .tt extension, which you'll find within the files generated in the process, linked to the model's files.

The reason to include these files is double: they allow the user to decide the way the code is generated, and they facilitate the creation itself (remember that Visual Studio uses CodeDOM internally among other techniques to generate code).

Take a look at the classes generated and you'll learn how the Department class has been created, along with an AdventureWorks2014Entities class, which will be the starting point for data manipulation.

Well, now we need controllers and views to present the user with the typical CRUD options for data manipulation. Once again, the IDE comes to help. Select Add Controller, and a dialog box will appear to select the type of controllers available.

Note

Note that you'll need to compile the project first, since actual assemblies might be required for code generation.

Additionally, keep in mind that due to the natural integration with Entity Framework, an option covering all required controllers and views will be offered. So, in the Add Scalffold dialog box, select the MVC 5 Controller with Views, using Entity Framework option. This will generate all the required code to test the basic CRUD data options:

The Entity Framework data model

You will still be asked about the model to use (Department, in my case), and about the DataContext class (AdventureWorks2014Entities). When the assistant finishes, several new files will have been generated.

First, we'll have a new DepartmentsController controller, which includes the CRUD operations I mentioned earlier. In addition, a new Departments folder appears, showing five new views, corresponding to Create, Delete, Details (to view only one department), Edit, and Index, which shows the whole list of departments, along with some links that will allow you to access the rest of options.

The first lines of that controller class indicates the suggested way to operate:

private AdventureWorks2014Entities db = new AdventureWorks2014Entities();

// GET: Departments
public ActionResult Index()
{
  return View(db.Departments.ToList());
}

The DBContext object will recover all the departments and convert them into List<Department>, which is the model the view expects (take a look at the Index.cshtml file in the Views/Departments area). When launching it, you'll need to reference the controller in the URL, since by default, the application is configured to present the Home controller and the Index action method.

If you type http://localhost:[portNumber]/Departments, the routing pattern will take you to the Index method in the Departments controller, and the following list will show up (it doesn't matter which browser you use, of course):

The Entity Framework data model

If everything goes fine, you'll be able to change data using the Edit and Delete links that the view presents automatically, and a selection of the Details option will take you to a different view, showing just the selected element.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.198.94