Entity Framework (EF)
Entity Framework (EF) is developed by Microsoft which automates the database insert,Update,select and delete (CRUD) operations without manually coding. ER increase the development time because database-related task is done without long code.
This post will help you understand ER operation. This post is designed for beginners as well as experts both. Step by step instruction is given to display records from SQL Server.
Post Detail
- Language C#
- IDE : Visual Studio 2019
- ASP.Net MVC Application
- SQL Server 2012
Step 1 : Install Entity Framework (EF)
Goto Tools Menu > Nuget Package Manager > Manage Nuget Packages for Solution
Click Browse and search Entity Framework select EF as given in the picture and install.
Step Two : Make Model
Database Structure
Required Namespace :
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
[Table("stu")]
public class TblStu
{
[Key]
public int roll { get; set; }
public string name { get; set; }
public string
city { get; set; }
}
Step Three : DBcontext
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using EntityFramwork.Models;
namespace EntityFramwork.Models
{
public class EmpDBContext : DbContext
{
public DbSet<TblStu> stulist { get; set; }
}
}
EmpDBContect is user defined class that inherit Dbcontect class for access database.
Database connection string name in web.config file must be matched with EmpDBContext name.
<connectionStrings>
<add name="EmpDBContext" connectionString="Data Source=DESKTOP-U10HCN5\SQLEXPRESS;Initial
Catalog=girfa_tmp;Integrated Security=true;" providerName="System.Data.SqlClient" />
</connectionStrings>
Note : Connection string name must be matched with
EBDBContext
Step Four : Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EntityFramwork.Models;
namespace EntityFramwork.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
EmpDBContext db = new EmpDBContext();
List<TblStu> data = new List<TblStu>();
data = db.stulist.ToList();
return View(data);
}
}
}
Step Five : View
@model IEnumerable<EntityFramwork.Models.TblStu>
@{
ViewBag.Title = "Home Page";
}
<table border="1">
<tr>
<th>Roll</th>
<th>Name</th>
<th>City</th>
</tr>
@foreach (var
item in Model)
{
<tr>
<td>@item.roll</td>
<td>@item.name </td>
<td>@item.city </td>
</tr>
}
</table>
No comments:
Post a Comment