
Asp.NET MVC framework has upgraded itself rapidly, and a lot of whole features are being added/supported. I last worked with Asp.NET MVC 3 with LinQ Based Web Application. While checking out 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 an easier start with these. I am using Visual Studio 2010 and SQL Server 2008 as the development environments for 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 Visual Studio to work with Asp.net MVC 4 . Download it from the official site. Since the Microsoft .NET platform introduced the web platform installer, I find it very easy to install and integrate new products/patches/updates. As soon as this 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 consider how many websites you signed up with and 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 have encountered this kind of issue several times. From this, the idea came that an application should be developed that would contain all this password information in a useful and organized way.
What about security? Why will people believe this application? Yeah, I know. Don’t get too serious about it. Even so far, I haven’t made a strict plan yet. Let’s just make the assumption for this tutorial at this moment.
Create New Project:
Creating a new project is similar to the previous MVC 3 version. We will need to specify the template engine, tell whether to create a test project or not, etc. After creation, a basic structure is already given. If we run this, we will see the home page as follows:
Let’s Start With Creating A Model Class:
if you are already an 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 by defining a model class that will be used to create controllers/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 Passwords { get; set; }
}
}
Code language: JavaScript (javascript)
As you can notice here, we have created two classes: one for the database table/entity with the name ‘Password’ and another one for DbContext, which will act as the database container in our application. When you 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 the ‘Add’ -> ‘Controller’ option.
It will lead you to a new controller creation window, where you can select the model class and DataContext class to be mapped with and the template engine as well. Set them as in the image below.
By defining the view template, we create views at the same time as the controller instead of creating them separately.
Connect To Database Server:
As we have created the controller/model/views, it’s 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" />
Code language: HTML, XML (xml)
Name it with your DBContext class and set the server/database name according to your 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 the Entity Framework: It facilitates creating databases/tables from the defined entity automatically without worrying about manually doing that 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 above properly, you should now be able to build the application successfully and run it properly as well. After running use the URL “http://localhost:{port}/Password” to navigate to our recently implemented controller:
Here, you can test the creation of new/update/delete options and whether they are functional or not (They should be :). Now, if you go and check your database, you should find it created properly on the SQL server database:
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 existing one? As the database already exists, the entity framework won’t create or modify it on its own. So, let’s prepare for such a scenario so that we can easily update our database in the future whenever a new modification occurs right from the Visual Studio environment.
If you are not familiar with Visual Studio’s Package Manager console, I am happy to introduce you to it. To launch it, use Visual Studio’s Tools -> Library Package Manager -> Package Manager 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.
Code language: CSS (css)
Now execute the ‘Add-Migration’ command, which will create a scaffold template for 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.
Code language: JavaScript (javascript)
As you can see here, when we 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 let’s execute the ‘update-database’ command, which will make the necessary changes to the 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.
Code language: JavaScript (javascript)
We are done with the database update completely. 🙂 I like this feature a lot, and I think other developers should also, as it will save a lot of time to set up/modify the database.
What’s Next?
Well, do some exercises with various scenarios and see if the application is working fine or not. Ask any questions below by commenting. You can follow the asp.net site’s tutorial series for more references. Happy coding 🙂
Discover more from CODESAMPLEZ.COM
Subscribe to get the latest posts sent to your email.
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/
This is my sample data from database,
ID Name ImageUrl
1 a notous.blob.core.windows.net/images/1-9.jpg
2 b notous.blob.core.windows.net/images/10_discount-150×150.jpg
3 c 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