Adding Entity Framework


In this post, we will talking about some improvements to do in our application. We will introduce E.F. That don’t have nothing to see with MVP pattern but we will use the Project of the previous post about MVP. In any case, you can apply this improvements in other projects.

The first step is create the database. In our case a book store database.

1

After create the database, we need to create a ADO.NET Entity Data Model

2

We follow the instructions and we can select the objects to import (Table, Views, procedures, …). In our case we are going to select the tables (we can add, remove, update later).

3

In our Diagram, and if we don’t have the foreign keys in the database or we want to add additional associations in the model, we can do it through the Diagram. To do it, we need to select one entity > Add new > Association.

4

After that, we select the relation (the line) and we need to specify the fields of the relation.

5

After finish the associations, our model should be something like that:

6

Next step is separate our entities. By default, the entities are been created in the same folder and Project than our model. This not respect the X-Layer design, so we should have the entities in another Project. Do that is very easy from versión 5.X of Entity framework. We only need to move the “.tt” file to the Entities Project.

7

When we have the file in the other Project, we need to change the file to put where are located the model in the the inputFile variable.

8

If all Works fine, we can see that our classes are been created in this new Project. Now we have all separated, so we can continue. We need to take into account that if we modify something from our Model, we need to come to this file and make some modification (or only save again) to reload the changes in this file.

We have created a new class to connect to E.F. and retrieve data

9

Now we only need to change our presenter to call this class instead the previous one and change the data source. (We have removed the old Book entity and replace by the new one of E.F.). Probably we are going to get an error trying to connect, due to the local database (“Error finding books. No connection string named ‘BookStoreEntities’ could be found in the application config file.”). We need to add the connection to the Project config file (we can see it in the Model Project) and add the EntityFramework library (EntityFramework.SqlServer.dll).

We can see that now, the result are retrieved from the database.

10

Leave a Reply

Your email address will not be published. Required fields are marked *