Entity Framework 5 Code First in MVC 4 for · PDF fileEntity Framework 5 Code First in MVC 4...

download Entity Framework 5 Code First in MVC 4 for · PDF fileEntity Framework 5 Code First in MVC 4 for ... don’t worry since after this tutorial you will be able to perform basic CRUD

If you can't read please download the document

Transcript of Entity Framework 5 Code First in MVC 4 for · PDF fileEntity Framework 5 Code First in MVC 4...

  • Entity Framework 5 Code First in MVC 4 for beginners

    A database can be created using Code First approach in Entity Framework 5. We will create a simple application that will save recipe of dishes and information of writer of recipe. Its demo application is linked at the end which will help to things understand the concept easily.

    First, we should understand what Entity Framework is.

    Database First

    The first iteration of Entity Framework, which came as part of .NET 3.5 and VisualStudio 2008, enables developers to create this model by reverse engineering an existing database into an XML file. The XML ends with the EDMX extension which can be viewed with a designer, and it can be customized to better suit your domain. Model First

    With the release of Visual Studio 2010 and .NET 4, the second version of Entity Framework was also released. This version, called Entity Framework 4, aligned it with the .Net version. A new feature that was added was Model First. Model First enabled you to design conceptual model in the visual designer which enabled database creation based on the model. Model First allows developers working on new projects that do not have legacy databases to benefit too. Developers can develop the application domain by designing the conceptual model. The database is created from that process. Database First and Model First

    After you have designed the EDMX, you should let automatic code generation build classes based on the entities and their relationships. Developers can use them to represent domain objects. EF4. In .NET 3.5 and POCO

    Another critical change came in EF4. In .NET 3.5, the only way Entity Framework was able to manage in-memory objects was by requiring classes to inherit from Entity Object. This enabled the database to track the changes made. POCO (Plain Old CLR Object) was also introduced which enabled the Entity Framework to track changes to simpler classes without needing the Entity Object. This benefited developers as it allowed them to develop classes and use them. Code First

    Code First is a modeling path that lets the code define the domain model. This is beneficial for developers since they are at ease writing codes rather than using a designer. Developers can define the domain model through POCO.

  • With this approach you dont need to do anything with SQL Server because Code First is designed to create database purely from POCO classes. In Code First technique, models represent our tables in database and properties represent columns in table Note: We will work with two POCO classes so that we can focus on understanding of creation of database. We will make a change in our model, and then will see how to update database again to match our updated model. In this tutorial we will discuss:

    Creation of domain model using POCO classes Creation of database according to classes Scaffold the CRUD operators Change in Model and Updating Database

    Before proceeding, I want to make some terms easier for you like Scaffolding. Scaffolding is new feature introduced to create views and controller automatically. It is used to automatically generate the baseline of your application's CRUD (Create, Read, Update and Delete) without writing a single line of code. If you have not written any MVC application till now, dont worry since after this tutorial you will be able to perform basic CRUD operations in MVC using Entity Framework 5 Code First.

    So lets start our tutorial by understanding database structure.

    This is One to Many relationship which shows Writers may have written many Recipes but One Recipe is only and only written by one Writer

  • Creating MVC 4 Project :

    Open your Visual Studio 2012 -> click on File -> New -> Project

  • Select Visual C# in left pane, and then select ASP.NET MVC 4 Web Application and name it KitchenApp

    And click Ok as shown in picture

  • In the next dialog box, select Empty Project Template, and I will add things manually that will help you to understand project in better way. Then select Razor in View engine drop down because it is recommended to use Razor engine and click Ok. This will create project with some basic files and folders that we will use further in our tutorial.

  • Now your Project solution should look like

  • According to our project, we need two Entities. First Writer will hold information regarding Writer and we also need Recipe for Recipe information.

    In MVC, we have basic structure of project which tells us that operations related Models should be done in Model folder. Model folder will contain all model classes like Writer and Recipe. Views folder will contain pages that will be shown to user. Controllers folder will have Action method that will co-ordinate with models and Views. This will help us to easily maintain UI pages separate and Model and Controllers logic separately

    Lets add Model class Writer in Models Folder. To add class, right click on Models folder and then Add New Item. This will open dialog box.

  • Expand Visual C#, and select Code from left pane. Then select Class and name is Writer.cs, and click Add button.

  • This will add a class Writer in Models folder and repeat this step to add Recipe.cs class

    After this, the Solution Explorer should have both these files added -

    Double click on Writer.cs, and add following code in this class

    publicclassWriter { publicint Id { get; set; }

    [Required] publicstring Name { get; set; } publicvirtualICollection Recipes { get; set; } }

    This code shows Id that will be used as primary key in our database table. Entity Framework identifies itself property that should be primary key by searching Id in property or Class Name ending with Id, compiler will search for this sequence of character in class and will make it primary key.

    Name property will be Name column and [Required] shows Name is required and this column cant be null in table. Note that [Required] will show you error because they reside in System.ComponentModel.DataAnnotations name space to use Annotation tags you just need to add following name space

    usingSystem.ComponentModel.DataAnnotations;

  • As we know that one writer can have multiple Recipes, thats why ICollection has been added. It will tell SQL Server relationship between Writer and Recipe Table. Recipes property will hold list of Recipes this means Writer may have many Recipes associated with Writer.

    Now double click on Recipe.cs and add following code in Recipe.cs class

    publicclassRecipe { publicint Id { get; set; } [Required] publicstring Content { get; set; } publicintWriterId { get; set; } publicvirtualWriterWriter { get; set; } }

    Here Id will become Id of Recipe table, and it will be auto incremented. Then we have Content that will hold formula of our recipe, and WriterId will be foreign key references to Id of Writer and in last

    publicvirtualWriterWriter { get; set; }

    This property will show that Recipe will have only one Writer associated with one Recipe.

    Up to here, both your classes should look like

    Writer.cs

  • Recipe.cs

  • Now we need to configure our project for Entity Framework 5.0. To configure our project for Entity Framework 5.0 we need to install Entity Framework 5.0. The steps to install Entity Framework 5.0 are as follows.

    Click on Tools -> Library Package Manager and click on Package Manager Console this will open panel at bottom of Visual Studio 2012

  • Here is snap shot

  • Now to install Entity Framework 5.0, you just need to write following command

    PM> Install-Package EntityFramework -version 5.0.0.0

    You will see confirmation after few seconds till Visual Studio 2012 downloads and installs Entity Framework 5.0 for your project

    It will also add some code in web.config which is at root in solution explorer

    Now lets write a simple class that will inherit from DbContext class

    The DbContext class is responsible for interacting with data as objects is System.Data.Entity.DbContext. This class will be responsible for interacting with our Database for creating database, creating tables, and for all CRUD operations. It will also connect to database, and there will be no need to initialize any SqlConnection, SqlAdapter or anything else like we do traditionally in SqlClient

    http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=vs.103)

  • Adding Context Class

    Add a simple class as we added model in previous steps

    To add class, Right click on Models folder in solution explorer and New Item this will open dialog box, name your class as KitchenContext

    After creating this class, add the following name space in the class

    usingSystem.Data.Entity;

    Then paste the following code. Your class should look like (Must inherit your class with DbContext)

    publicclassKitchenContext : DbContext { publicDbSet Writers { get; set; } publicDbSet Recipes { get; set; } }

    Here KitchenContext class is inherited from DbContext class to get Entity Framework functionalities.

    There are two properties in this class

    publicDbSet Writers { get; set; }

  • This property shows that we need table of Writer model and its table name will be Writers and same for other property. PART 1

    We can get all writers in table by making object of KitchenContext class that will perform all transactions with database. We will cover this code in further tutorial also.

    privateKitchenContextdb = newKitchenContext();

    db.Writers.ToList();

    Above two lines of code will return list of write