Entity Framework 5 Code First in MVC 4 for beginners

Similar documents
To install Multifront you need to have familiarity with Internet Information Services (IIS), Microsoft.NET Framework and SQL Server 2008.

Getting Started with Telerik Data Access. Contents

Creating Database Tables in Microsoft SQL Server

Creating and Issuing the Workstation Authentication Certificate Template on the Certification Authority

The full setup includes the server itself, the server control panel, Firebird Database Server, and three sample applications with source code.

VB.NET - WEB PROGRAMMING

Learn how to create web enabled (browser) forms in InfoPath 2013 and publish them in SharePoint InfoPath 2013 Web Enabled (Browser) forms

Configuring.NET based Applications in Internet Information Server to use Virtual Clocks from Time Machine

Visual COBOL ASP.NET Shopping Cart Demonstration

Sitecore Ecommerce Enterprise Edition Installation Guide Installation guide for administrators and developers

Jolly Server Getting Started Guide

Paging, sorting, and searching using EF Code first and MVC 3. Introduction. Installing AdventureWorksLT database. Creating the MVC 3 web application

STATISTICA VERSION 10 STATISTICA ENTERPRISE SERVER INSTALLATION INSTRUCTIONS

Deploying an ASP.NET Web Application to a Hosting Provider using Visual Studio

R i o L i n x s u p p o r r i o l i n x. c o m 1 / 3 0 /

GoDaddy (CentriqHosting): Data driven Web Application Deployment

Instructions for Configuring a SAS Metadata Server for Use with JMP Clinical

Administrator s Upgrade Guide.

Moving the Web Security Log Database

Installing the ASP.NET VETtrak APIs onto IIS 5 or 6

MS WORD 2007 (PC) Macros and Track Changes Please note the latest Macintosh version of MS Word does not have Macros.

Bitrix Site Manager 4.1. User Guide

Building an ASP.NET MVC Application Using Azure DocumentDB

DocumentsCorePack for MS CRM 2011 Implementation Guide

How to FTP (How to upload files on a web-server)

Secure Messaging Server Console... 2

TIBCO Spotfire Metrics Prerequisites and Installation

ScriptLogic File System Auditor User Guide

Getting Started with Elastic DB Database Tools with Azure SQL

ConvincingMail.com Marketing Solution Manual. Contents

Capture Pro Software FTP Server System Output

How to Create a Delegated Administrator User Role / To create a Delegated Administrator user role Page 1

On-premise and Online connection with Provider Hosted APP (Part 1)

Backup and Restore with 3 rd Party Applications

Data Tool Platform SQL Development Tools

Analytics Configuration Reference

McAfee One Time Password

How to configure the DBxtra Report Web Service on IIS (Internet Information Server)

How to Move Mail From Your Old POP Account To Exchange Using Outlook 2010

INTEGRATING MICROSOFT DYNAMICS CRM WITH SIMEGO DS3

Moving the TRITON Reporting Databases

How to test and debug an ASP.NET application

SalesPad for Dynamics GP DataCollection Installation & Setup

SECURE MOBILE ACCESS MODULE USER GUIDE EFT 2013

0651 Installing PointCentral 8.0 For the First Time

Introduction. Configurations. Installation. Vault Manufacturing Server

MS Enterprise Library 5.0 (Logging Application Block)

SAS Visual Analytics 7.2 for SAS Cloud: Quick-Start Guide

Composite.Community.Newsletter - User Guide

Workflow Conductor Widgets

BUILDER 3.0 Installation Guide with Microsoft SQL Server 2005 Express Edition January 2008

14 Configuring and Setting Up Document Management

Handout: Creating Forms in Word 2010

SQL Server 2005: Report Builder

How To Use Query Console

EventSentry Overview. Part I Introduction 1 Part II Setting up SQL 2008 R2 Express 2. Part III Setting up IIS 9. Part IV Installing EventSentry 11

Building and Using Web Services With JDeveloper 11g

SharePoint Wiki Redirect Installation Instruction

Installing Cobra 4.7

SelectSurvey.NET Developers Manual

RoomWizard Synchronization Software Manual Installation Instructions

Qlik REST Connector Installation and User Guide

Appendix K Introduction to Microsoft Visual C++ 6.0

Create a New Database in Access 2010

Stored Documents and the FileCabinet

ibolt V3.2 Release Notes

Authoring for System Center 2012 Operations Manager

Amman Jordan Mob: Tel:

SAS Business Data Network 3.1

Working with SQL Server Integration Services

ORACLE BUSINESS INTELLIGENCE WORKSHOP

Installation of IR under Windows Server 2008

E-Commerce Installation and Configuration Guide

INFOPATH FORMS FOR OUTLOOK, SHAREPOINT, OR THE WEB

Setting Up ALERE with Client/Server Data

Tool Tip. SyAM Management Utilities and Non-Admin Domain Users

Writer Guide. Chapter 15 Using Forms in Writer

Windows Server Update Services 3.0 SP2 Step By Step Guide

Legal Information Trademarks Licensing Disclaimer

OUTLOOK ANYWHERE CONNECTION GUIDE FOR USERS OF OUTLOOK 2010

O Reilly Media, Inc. 3/2/2007

Abila Millennium. Installation Guide

Monitoring Inventory. Inventory Management. This chapter includes the following sections:

Installation Instruction STATISTICA Enterprise Server

Smart Connection 9 Element Labels

Outlook Data File navigate to the PST file that you want to open, select it and choose OK. The file will now appear as a folder in Outlook.

Issue Tracking Anywhere Installation Guide

Secret Server Installation Windows Server 2008 R2

Getting Started with the Ed-Fi ODS and Ed-Fi ODS API

Web Forms for Marketers 2.3 for Sitecore CMS 6.5 and

PC Monitor Enterprise Server. Setup Guide

Printer Connection Manager

Using SQL Server Management Studio

WebSpy Vantage Ultimate 2.2 Web Module Administrators Guide

Sample Table. Columns. Column 1 Column 2 Column 3 Row 1 Cell 1 Cell 2 Cell 3 Row 2 Cell 4 Cell 5 Cell 6 Row 3 Cell 7 Cell 8 Cell 9.

Programming in C# with Microsoft Visual Studio 2010

ODBC Driver Version 4 Manual

Transcription:

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 inmemory 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 don t 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, don t worry since after this tutorial you will be able to perform 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 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 coordinate with models and Views. This will help us to easily maintain UI pages separate and Model and Controllers logic separately Let s 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<recipe> 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 can t 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, that s 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 let s 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

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<writer> Writers { get; set; } publicdbset<recipe> Recipes { get; set; } } Here KitchenContext class is inherited from DbContext class to get Entity Framework functionalities. There are two properties in this class publicdbset<writer> 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 writers. So up to here we have now created kitchencontext class and class should look like Now, let s focus on Entity Frame work. We will tell it where to create our database and what should be the name of database by putting Connection String in web.config file. The actual database can be generated without mentioning connection string, and the name of database will be same as context class. Its good practice to mention connection string so that we can name our database manually and we can modify user of database. To do this, open web.config file from solution explorer and add connection string next to ConfigSections tag. In our case, the connection string for data base is as follows <connectionstrings> <addname="kitchencontext"connectionstring="data Source=DOTNET-PC\MSSQLSERVER2K8;Initial Catalog=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, but you can give any name. In our case, ID=sa and password is 1234 but you need to change it according to your SQL server setting. Your web.config should look like We have completed all the required tasks for making our database.

Creating Database with Migration Migration will help us to update our database with our models if the models are changed Click on Tools -> Library Package Manager and click on Package Manager Console. This will open panel at bottom of Visual Studio 2012 And execute command PM> Enable-Migrations You 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 command You need to make AutomaticMigrationsEnabled = true so that you can update database easily otherwise you will need to do additional steps to update database. AutomaticMigrationsEnabled = true is better when you don t want to track information of changing of database otherwise it is recommended to use AutomaticMigrationsEnabled = false. Seed method is automatically invoked after creation of database. This method is used to insert some test data in database in our case we will add data from our pages

To create database, you all need to do PM> Update-Database This means database is created;now open SQL server to confirm our database has been created Note that the name of Database is same which was mentioned in connection string, and name of tables same as properties created in KitchenContext.cs And column names are same as properties created in Writer.cs and Recipe.cs

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

The following dialog box will open Note: If you don t get Template MVC Controller with read/write actions and views using Entity Frame work, then please check for ASP.NET MVC Tools Update

We are adding controller for Writer model with the name WriterController. Select Template, select model class, and in the last DataContext class that s KitchenContext. Click Add, and this will add controller 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 of page Change it to

Do this for all Create and Edit pages, and your application is ready. Press control+f5 to execute 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. 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 display Second parameter: Which action to redirect Third 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 Recipe Here 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 your Changing 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 Manager Console This will update your database according to your changed model Now you can manually add this field in your page or you can delete RecipeController and Recipe folder in Views, and add RecipeController again. In my case I am adding controller again by deleting previous created 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 and Edit.cshtml

Then add link for Writers List Again 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 applied Note: To view validation messages click on Create button without filling form with data