segunda-feira, 4 de abril de 2016

Entity Framework

This post is about entity framework and how to use it to make, almost with a simple mouse click, the CRUD (create, read, update and delete) operations over a table.

Let's start by creating a web MVC project with Visual Studio 2015.







 Now we add a database with a table for books, for that we use the right mouse button in the Data Connections link over the Server Explorer window and then choose Add Connection...

 When the database is ready use the right mouse button again, like so.

These are the fields for the table.
When everything is ready just click the Update option and the following window will popup.

On this one just click the Update Database button, if you can't maybe you have some error back in the create table script.
 After the executation of the script you can check the new table in the database.
 If it's not showing try refreshing the tables, be aware that the refresh option only refreshes the section selected so make sure tables is selected before trying to refresh.


When the table is finally created let's go over the Solution Explorer and use the right mouse button to create a new item of type ADO .Net Entity Data Model. You should right click the folder of the models so VS saves the data model in that folder.
 
 If the option is not visible you must choose new item and then search ADO.
Define a name for the data model, or keep the one that's already there and then choose EF Designer from Database.
Click next and choose the data connection or the database.
And then you can say Yes so that the VS copies your database into the App_Data folder of your project.
Finally choose the table books of the database.
When you click finish the VS will go over your table and build a model.

Next, we must compile (build) our project, so that the model we created can be used.
The following step is simple, we create a controller with all the options we want. To do that use the right mouse button and click the controllers folder and choose add - controller.

In the window that pops click on MVC 5 controller with views, using Entity Framework.
Now indicate the data model, the data source and the name to the controller.
And then we wait.

In the end of this process we get a controller with code and views ready to go.





Sem comentários:

Enviar um comentário