CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact
Home Development Getting Started With Asp.NET MVC 4 And Entity Framework

Getting Started With Asp.NET MVC 4 And Entity Framework

Rana Ahsan February 27, 2013 2 Comments


 Getting Started With Asp.NET MVC 4 And Entity Framework    

Asp.NET MVC framework has upgraded itself rapidly and a lot of whole features are being added/supported. I lastly worked with Asp.NET MVC 3 With LinQ Based Web Application. While checking out the MVC 4, I got familiar with Entity framework and MVC 4’s new look and feel etc. That’s why I have decided to share my first experience with Asp.NET MVC 4 And Entity Framework based web application development basics so that readers can have more easier start with these. I am using visual studio 2010 and SQL server 2008 as development environment of this exercise.

If you are an previously familiar with Asp.NET MVC, you might want to read the new mobile features and other features improvement/addition details.

Download And Install MVC 4:

First, we will need to set up our visual studio to work with asp.net MVC 4 . Download it from official site. Since Microsoft .NET platform introduced web platform installer, I find it very easy to get new product/patch/update installed and integrated very easily. As soon as it is done, we can move ahead to create our new exercise project with Asp.NET MVC 4 And Entity Framework.

The Exercise Project Background:

Did you ever think in total how many websites you signed up with? How many password combinations you used on all those sites? Can you remember the password of a site that you visited several months ago? Well, I did fell in this kind of issues several times. From this the idea came that an application be developed which will contain all these password information in a useful and organized way.

What about security? Why people will believe this application? Yeah, I know, don’t get too serious about it :D. Even so far, I don’t made a strict plan yet. Just let’s make the assumption for this tutorial at this moment.

Create New Project:

creating new project is similar to previous MVC 3 version. We will need to specify template engine, tell whether to create test project or not etc. After creation, a basic structure is already given. If we run this, we will see the home page like as follows:

Asp.NET MVC 4 HomePage

Lets Start With Creating A Model Class:

if you are already a Asp.NET MVC developer, you might know that, it is possible to scaffold a controller and views from a defined model. That’s why, we will start with defining a model class which will be used to create controller/views automatically. In our projects ‘Models’ directory, create a new C# class as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace MyPasswords.Models
{
    public class Password
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public string Category { get; set; }
        public string URL { get; set; }
        public string AppUserName { get; set; }
        public string AppPassword { get; set; }
    }

    public class PasswordDBContext : DbContext
    {
        public DbSet<Password> Passwords { get; set; }
    }
}

As you can notice here, we have created two classes one for the database table/entity with name ‘Password’ and another one is for DbContext which will act as the database container in our application. When you will create more tables, you can create this DbContext class separately as well.

Create Controllers And Views:

to create a new controller from the above created model, right-click on the ‘Controllers’ directory and use ‘Add’ -> ‘Controller’ option.
create new controller

It will lead you to a new controller creation window where you will be able to select the model class and DataContext class to be mapped with and template engine as well. Set them as in the image below.
New Controller Window
By defining the view template, we are creating views at the same time of controller creation, instead of creating them separately.

Connect To Database Server:

As we have create controller/model/views, its time to connect to the database server. In your web.config file, add a new connection string as below:

  <add name="PasswordDBContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=MyPasswords;Integrated Security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />

Name it with your DBContext class and set server/database name as per your own preference. Notice that, we haven’t created any database on our SQL server yet. Yes, and it’s not required at all. Here is the magic of Entity framework, it facilitates us to create database/tables from the defined entity automatically without worrying to do that manually via SQL management studio.

Build And Run Our Asp.NET MVC 4 And Entity Framework Based Mini Application:

so, if you have done all the steps as above properly, you should now be able to build the application successfully and run properly as well. After running use the URL “http://localhost:{port}/Password” to navigate to our recently implemented controller:
Controller Index Page

Here you can test the create new/update/delete all options whether they are functional or not ( They should be ๐Ÿ™‚ . Now if you go and check your database you should find it created properly on SQL server database:
Updated SQL Server DB

Preparing For Future Modification:

So, far we have done a good job. Now, what if we need to add a new entity to the database or modify an entity? As database is already exist, entity framework won’t go to create or modify it of its own. So, lets prepare for such scenario so that we can update our database in future whenever a new modification occurs, right from visual studio environment, easily.

Here, I am happy to introduce you with visual studio’s Package manager console, if you are not familiar already. Use visual studio’s ‘Tools’->’Library Package Manager’->’Package Manager Console’ to launch this console.

First use the “Enable-Migrations” command in the console and you should have an output as below:

PM> Enable-Migrations -ContextTypeName MyPasswords.Models.PasswordDBContext
Checking if the context targets an existing database...
Code First Migrations enabled for project MyPasswords.

Now Execute ‘Add-Migration’ command, which will create a scaffold template from your entity. Output should be as follows:

PM> add-migration Test
Scaffolding migration 'Test'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration 201302260652175_Test' again.

As you can see here, when we will make changes in our model entities, we will have to run this command again specifying the generated template name. The template file should look something like as follows:

namespace MyPasswords.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class Initial : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Passwords",
                c => new
                    {
                        ID = c.Int(nullable: false, identity: true),
                        Title = c.String(),
                        Category = c.String(),
                        URL = c.String(),
                        AppUserName = c.String(),
                        AppPassword = c.String(),
                    })
                .PrimaryKey(t => t.ID);
            
        }
        
        public override void Down()
        {
            DropTable("dbo.Passwords");
        }
    }
}

Now lets execute the ‘update-database’ command which will make necessary changes to database:

PM> update-database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying code-based migrations: [201302260652175_Test].
Applying code-based migration: 201302260652175_Testl.
Running Seed method.

And we are done with database update completely ๐Ÿ™‚ . I like this feature a lot and I think, other developers should also as it will save a lot time to set up/modify database.

What’s Next?

Well, do some exercise with some various scenario and see if application is working fine or not. Ask any questions below by commenting. you can follow the asp.net site’s tutorial series as more references. Happy coding ๐Ÿ™‚

Related

Filed Under: Development Tagged With: .net, web application

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Comments

  1. Kalyan (@kalyanms1) says

    April 24, 2013 at 4:27 pm

    Hi
    Thanks for sharing the screenshots and explaining scaffolding in MVC4. To understand each template purpose you can read the below post http://www.techbubbles.com/aspnet/scaffolding-in-asp-net-mvc4/

    Reply
  2. anil says

    August 19, 2013 at 5:30 am

    This is my sample data from database,

    ID Name ImageUrl

    1 a http://notous.blob.core.windows.net/images/1-9.jpg

    2 b http://notous.blob.core.windows.net/images/10_discount-150×150.jpg

    3 c http://notous.blob.core.windows.net/images/FB-button-341×341.png

    I want display this data not for same This ImageURL display as image in My view Using ASP.NET MVC,

    And also At the time of insert also after uploading the image save in database Like above(its possible???)

    please help me,I am new to this MVC

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • PHP HTML5 Video Streaming Tutorial
  • How To Work With JSON In Node.js / JavaScript
  • Generate HTTP Requests using c#
  • How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
  • How To Work With CodeIgniter Pagination
  • LinQ To SQL Database Update Operations In C#
  • Get Facebook C# Api Access Token
  • How To Work With Multithreaded Programming In C#.NET Application
  • Getting Started With HTML5 Web Speech API

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • intolap on PHP HTML5 Video Streaming Tutorial
  • manishpanchal on PHP HTML5 Video Streaming Tutorial
  • Rana Ghosh on PHP HTML5 Video Streaming Tutorial
  • ld13 on Pipe Email To PHP And Parse Content
  • Daniel on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2021 · CodeSamplez.com ·

Copyright © 2021 ยท Streamline Pro Theme on Genesis Framework ยท WordPress ยท Log in