Assalamualaykum Wr Br..:)
Today we build MVC web app. with Entity Framework. Lets add new table TblEmployee in EF_DBFirst database as shown below:
The respective script is:
CREATE TABLE [dbo].[TblEmployee] (
[Id] INT NOT NULL,
[Name] VARCHAR (50) NOT NULL,
[Gender] VARCHAR (50) NOT NULL,
[City] VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
Now create new application of MVC_EF and add new controller EmployeeController.cs, Employee.cs in Model, EmployeeContext.cs in Model and Display.cshtml in Views/Employee. As per the table design generate a class with name Employee.cs in Model as shown below:
In above class, Table attribute describes class Employee as per the table TblEmployee and Table attribute exists in System.ComponentModel.DataAnnotations.Schema namespace. Now we need to create connection string which is done in web.config as shown:
Please notice that we have provided name=”EmployeeContext”hence we create a dbcontext class as shown below with name EmployeeContext.cs where we define property which returns whole data of table employee.
Now focus on controller class which is responsible for routing the user requests and response. Design the controller class as shown below:
In controller we create employeecontext class object and access single record with respect to id passed from frontend as a parameter to Details Controller. The Linq query is (emp => emp.Id == id)
emp is temporary variable which cross checks with parameter id with existing db Id, if matches then displays data of record and returns to view. view is designed as shown:
the first line of above states that this view accesses model Employee and @Model.Name is retrieved from db table. Finally if i pass the url the following output is seen.
Thats all for the day.Jazakallah Khair.