Monday, 25 January 2016
First MVC 4 Sample Application With Entity Framework Code-First Approach
In this example you will learn how to create simple MVC 4
application using CRUD operation (Create, Read, Update, Delete ) with Enity
Framework and SqlServer Database.
Open VisualStudio -> New Project -> Select Visual
Basic / Visual C# -> Web -> ASP.NET MVC 4 Web Application
Give a Name to your project and then press Ok.
A New project dialog box appears with various project
templates. Here we are using Internet Application and Search Engine Razor and
then press Ok. It will add require folder and files automatically.
This is a default template of an application.
Here our aim is to create a Student profile application. We
need to create a Model for this application it will automatically create table
in database with columns what we are mention properties in Model class.
First Create a Model Class:
In Solution Explorer -> Right Click on Model -> Add
-> Class
Give a name to the class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations; //Need to add this
namespace
using System.Data.Entity; //Need to add this namespace
namespace MvcBookApp.Models
{
public class StudentDetails
{
[Key]
public int StudentId { get; set; }
public string StudentName { get; set; }
public string FatherName { get; set; }
public string Class { get; set; }
}
public class StudentDetailContext : DbContext
{
public DbSet<StudentDetails> Student
{
get;
set;
}
}
}
Next open web.config file modify connection string as
shown image below with your datasource and Initial-Catalog whatever you want.
Next add Controller to our application
Click on Solution Explorer -> RightClick on Controller
-> Add -> Controller
Change the name without removing Cotroller text(In
controller name Controller is mandatory before that add your own name).
Here StudentDetails and StudentDetailContext doesn't appear because of we need to build an application first.
Model class as StudentDetails
Data Context class as StudentDetailContext
Views Razor engine and then click on
add button.
Visual Studio create files and folders under your project
Run your application and appending StudentDetails to the URL
in the browser
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment