Entity Framework 5 Code First In MVC 4 For Beginners

Transcription

Entity Framework 5 Code First in MVC 4 for beginnersA database can be created using Code First approach in Entity Framework 5. We will create a simpleapplication that will save recipe of dishes and information of writer of recipe. Its demoapplication is linked at the end which will help to things understand the concept easily.First, we should understand what Entity Framework is.Database FirstThe first iteration of Entity Framework, which came as part of .NET 3.5 and VisualStudio 2008, enablesdevelopers to create this model by reverse engineering an existing database into an XML file. The XMLends with the EDMX extension which can be viewed with a designer, and it can be customized to bettersuit your domain.Model FirstWith the release of Visual Studio 2010 and .NET 4, the second version of Entity Framework was alsoreleased. This version, called Entity Framework 4, aligned it with the .Net version. A new feature thatwas added was Model First. Model First enabled you to design conceptual model in the visual designerwhich enabled database creation based on the model.Model First allows developers working on new projects that do not have legacy databases to benefittoo. Developers can develop the application domain by designing the conceptual model. The databaseis created from that process.Database First and Model FirstAfter you have designed the EDMX, you should let automatic code generation build classes based on theentities and their relationships. Developers can use them to represent domain objects.EF4. In .NET 3.5 and POCOAnother critical change came in EF4. In .NET 3.5, the only way Entity Framework was able to manage inmemory objects was by requiring classes to inherit from Entity Object. This enabled the database totrack the changes made. POCO (Plain Old CLR Object) was also introduced which enabled the EntityFramework to track changes to simpler classes without needing the Entity Object. This benefiteddevelopers as it allowed them to develop classes and use them.Code FirstCode First is a modeling path that lets the code define the domain model. This is beneficial fordevelopers since they are at ease writing codes rather than using a designer. Developers can define thedomain model through POCO.

With this approach you don’t need to do anything with SQL Server because Code First is designed tocreate database purely from POCO classes. In Code First technique, models represent our tables indatabase and properties represent columns in tableNote: We will work with two POCO classes so that we can focus on understanding of creation ofdatabase. We will make a change in our model, and then will see how to update database again tomatch our updated model.In this tutorial we will discuss: Creation of domain model using POCO classesCreation of database according to classesScaffold the CRUD operatorsChange in Model and Updating DatabaseBefore proceeding, I want to make some terms easier for you like Scaffolding. Scaffolding is new featureintroduced to create views and controller automatically. It is used to automatically generate the baselineof your application's CRUD (Create, Read, Update and Delete) without writing a single line of code. If youhave not written any MVC application till now, don’t worry since after this tutorial you will be able toperform basic CRUD operations in MVC using Entity Framework 5 Code First.So let’s start our tutorial by understanding database structure.This is One to Many relationship which shows Writers may have written many Recipes but One Recipe isonly and only written by one Writer

Creating MVC 4 Project :OpenyourVisualStudio2012- clickonFile- New- Project

Select Visual C# in left pane, and then select ASP.NET MVC 4 Web Application and name it KitchenAppAnd 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 tounderstand project in better way. Then select Razor in View engine drop down because it isrecommended to use Razor engine and click Ok. This will create project with some basic files and foldersthat 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 andwe also need Recipe for Recipe information.In MVC, we have basic structure of project which tells us that operations related Models should be donein Model folder. Model folder will contain all model classes like Writer and Recipe. Views folder willcontain pages that will be shown to user. Controllers folder will have Action method that will coordinate with models and Views. This will help us to easily maintain UI pages separate and Model andControllers logic separatelyLet’s add Model class Writer in Models Folder. To add class, right click on Models folder and then AddNew 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 Addbutton.

This will add a class Writer in Models folder and repeat this step to add Recipe.cs classAfter this, the Solution Explorer should have both these files added -Double click on Writer.cs, and add following code in this classpublicclassWriter{publicint Id { get; set; }[Required]publicstring Name { get; set; }publicvirtualICollection Recipe Recipes { get; set; }}This code shows Id that will be used as primary key in our database table. EntityFramework identifies itself property that should be primary key by searching Id inproperty or Class Name ending with Id, compiler will search for this sequence ofcharacter in class and will make it primary key.Name property will be Name column and [Required] shows Name is required and this column can’t benull in table. Note that [Required] will show you error because they reside inSystem.ComponentModel.DataAnnotations name space to use Annotation tags you just need toadd following name spaceusingSystem.ComponentModel.DataAnnotations;

As we know that one writer can have multiple Recipes, that’s why ICollection has been added. It will tellSQL Server relationship between Writer and Recipe Table. Recipes property will hold list of Recipes thismeans Writer may have many Recipes associated with Writer.Now double click on Recipe.cs and add following code in Recipe.cs classpublicclassRecipe{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 haveContent that will hold formula of our recipe, and WriterId will be foreign key referencesto Id of Writer and in lastpublicvirtualWriterWriter { 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 likeWriter.cs

Recipe.cs

Now we need to configure our project for Entity Framework 5.0. To configure our project for EntityFramework 5.0 we need to install Entity Framework 5.0. The steps to install Entity Framework 5.0 are asfollows.Click on Tools - Library Package Manager and click on Package Manager Console this will open panel atbottom of Visual Studio 2012

Here is snap shot

Now to install Entity Framework 5.0, you just need to write following commandPM Install-Package EntityFramework -version 5.0.0.0You will see confirmation after few seconds till Visual Studio 2012 downloads and installs EntityFramework 5.0 for your projectIt will also add some code in web.config which is at root in solution explorerNow let’s write a simple class that will inherit from DbContext classThe 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 anySqlConnection, SqlAdapter or anything else like we do traditionally in SqlClient

Adding Context ClassAdd a simple class as we added model in previous stepsTo add class, Right click on Models folder in solution explorer and New Item this will open dialog box,name your class as KitchenContextAfter creating this class, add the following name space in the classusingSystem.Data.Entity;Then paste the following code. Your class should look like (Must inherit your class with DbContext)publicclassKitchenContext : DbContext{publicDbSet Writer Writers { get; set; }publicDbSet Recipe Recipes { get; set; }}Here KitchenContext class is inherited from DbContext class to get Entity Frameworkfunctionalities.There are two properties in this classpublicDbSet Writer Writers { get; set; }

This property shows that we need table of Writer model and its table name will be Writers and same forother property. PART 1We can get all writers in table by making object of KitchenContext class that will perform all transactionswith database. We will cover this code in further tutorial also.privateKitchenContextdb newKitchenContext();db.Writers.ToList();Above two lines of code will return list of writers.So up to here we have now created kitchenContext class and class should look likeNow, let’s focus on Entity Frame work. We will tell it where to create our database and what should bethe name of database by putting Connection String in web.config file. The actual database can begenerated without mentioning connection string, and the name of database will be same as contextclass. Its good practice to mention connection string so that we can name our database manually andwe can modify user of database. To do this, open web.config file from solution explorer and addconnection string next to ConfigSections tag. In our case, the connection string for data base is asfollows connectionStrings addname "KitchenContext"connectionString "DataSource DOTNET-PC\MSSQLSERVER2K8;InitialCatalog KitchenDB;User ID sa;Password 1234"providerName "System.Data.SqlClient"/ /connectionStrings

Name of connection string should be same as context class name. In our case, name is KitchenContext,and you need to change source according to your pc. Catalog KitchenDB will be name of database, butyou can give any name. In our case, ID sa and password is 1234 but you need to change it according toyour SQL server setting. Your web.config should look likeWe have completed all the required tasks for making our database.

Creating Database with MigrationMigration will help us to update our database with our models if the models are changedClick on Tools - Library Package Manager and click on Package Manager Console. This will open panel atbottom of Visual Studio 2012And execute commandPM Enable-MigrationsYou will get confirmation as below

This will add Migrations folder in solution explorer that contains one class named as Configurations.cs

Well this class is very simple, this is default code written when class is created after executing commandYou need to make AutomaticMigrationsEnabled true so that you can update database easily otherwiseyou will need to do additional steps to update database.AutomaticMigrationsEnabled true is better when you don’t want to track information of changing ofdatabase otherwise it is recommended to use AutomaticMigrationsEnabled false.Seed method is automatically invoked after creation of database. This method is used to insert sometest data in database in our case we will add data from our pages

To create database, you all need to doPM Update-DatabaseThis means database is created;now open SQL server to confirm our database has been createdNote that the name of Database is same which was mentioned in connection string, and name of tablessame as properties created in KitchenContext.csAnd column names are same as properties created in Writer.cs and Recipe.cs

Creating Controllers and Views using Scaffolding optionWith the help of Scaffolding, you can create Controller and views with basic CRUD operations withoutwriting single line of code.To add Controller, right click on Controllers folder, then add, and then click on Controller.

The following dialog box will openNote: If you don’t get Template “MVC Controller with read/write actions and views” using Entity Framework, then please check for ASP.NET MVC Tools Update

We are adding controller for Writer model with the name WriterController. Select Template, selectmodel class, and in the last DataContext class that’s KitchenContext. Click Add, and this will addcontroller with basic code for CRUD operations and also views.

Repeat this step and add Controller for Recipe

Updated solution explorer looks like

You need to remove some automatic generated code from Create.cshtml and Edit.cshtml at bottom ofpageChange it to

Do this for all Create and Edit pages, and your application is ready. Press control F5 to execute andnavigate to writer like this http://localhost:1999/Writer. You don’t need to change your port number, inmy case it’s 1999.Create Writer by clicking on Create New link.

Now add the ActionLink code at the bottom of Index.cshtml in solution explorer - View - Writer - Index@ First parameter: Text to displaySecond parameter: Which action to redirectThird parameter: Name of Controller where action is present

To navigate from Recipe/Index to Writer/Index add the highlighted code after /table Now Click on

Create New RecipeHere you can see Writer that was added earlier. In this drop down we will have all writers

Even you don’t need to apply validation because Scaffolding has applied for yourChanging Model and updating Database:Now I am going to add Title property in Recipe.cs to add Title column in Recipes Table

To update your database you need to run Update-Database Command again in Package ManagerConsoleThis will update your database according to your changed modelNow you can manually add this field in your page or you can delete RecipeController and Recipe folderin Views, and add RecipeController again. In my case I am adding controller again by deleting previouscreated RecipeController and Recipe folder in Views.Make sure you have deleted previous RecipeControll and its views.

Click add and repeat this previous step for removing some auto generated code inCreate.cshtml andEdit.cshtml

Then add link for Writers ListAgain run your application by Control F5 and navigate to writer like this http://localhost:1999/Writer.You don’t need to change your port number, in my case it’s 1999.

Title field is added and [Required] validation is also appliedNote: To view validation messages click on Create button without filling form with data

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