C# Programming: ASP.NET MVC Full Database Tutorial

Tuesday, January 5, 2016

ASP.NET MVC Full Database Tutorial

Welcome to Database tutorial on Microsoft ASP.net MVC web app. You are at perfect place to give a jumpstart on asp mvc database.

Lets Start our Journey.

Lets Create Database First.
 Just goto Appdata folder and create a database and click on create new table.
The table definition is below:

CREATE TABLE [dbo].[users] (
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [username]   NVARCHAR (MAX) NOT NULL,
    [password]   NVARCHAR (MAX) NOT NULL,
    [email]      NVARCHAR (MAX) NOT NULL,

    CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([Id] ASC)
);

Here PK means primary key in our users table .

Lets Create our Model.
Model means just a class.

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

namespace mvc.Models
{
    [Table(Name = "users")]
    public class user
    {
        [Column(IsPrimaryKey = true, IsDbGenerated = true)]
        public int Id;
        [Column]
        public string username;
        [Column]
        public string password;
        [Column]
        public string email;
     


    }
}

//----To remove red lines just add a sqlite reference from references-------------------------

Lets Create A Context of user:
Context means just a easy way to connect with database table related with our user class here.
//-------context-----------------------
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Web;

namespace mvc.Models
{
    public class userContext : DataContext
    {
       // for local
        private const String ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|mydatabase.mdf;Integrated Security=True";
//for server:
 // Data source will be different check in your connection string in server

        public userContext()
            : base(ConnectionString)
        {
        }

        public Table<user> users;

    }
}

//----------------------------------------


View and Controller:
To show view and controller will be very bulky here because must of the codes are already given with the default asp mvc framework. So i suggest you to watch this video for full scenario. It is a complete tutorial on asp.net mvc web app with database.

The first of Databse Tutorial is here.



The second Video is here.

Ok guys you are now able to make a users list fetching data from databse table in asp mvc.
For further tutorials stay tuned. For javascript tutorial, you can visit my javascript blog:
https://javascripthero.blogspot.com

No comments:

Post a Comment