Hello Friends, In this tutorial we are going to see how to Display Records using Entity Framework in ASP.NET MVC. We are already familiar with the Entity Framework. Here we will see how we can Display Data using Entity Framework in ASP.NET MVC.

After completing this tutorial you will be able to understand:

  • How to Display Records using Entity Framework in  ASP.NET MVC.

Display Records using Entity Framework in ASP.NET MVC.

In our previous session, we have seen that how to save data using Entity Framework in ASP.NET MVC. Here we will Display the Data from SQL Server using Entity Framework in ASP.NET MVC.

Let’s Start with Creating Database and Tables in SQL Server.

Step 1 – Create Database using the following script.

CREATE DATABASE MYDB

Step 2 – Create Employee table using the following script.

USE [MYDB]
GO


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Employee](
[EmployeeID] [bigint] IDENTITY(1,1) NOT NULL,
[EmployeeName] [varchar](50) NULL,
[Gender] [varchar](10) NULL,
[Address] [varchar](50) NULL,
[State] [varchar](50) NULL,
[City] [varchar](50) NULL,
[Status] [varchar](20) NULL,
CONSTRAINT [PK__Employee__3214EC274AA9A371] PRIMARY KEY CLUSTERED 
(
[EmployeeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

Step 4 – Insert some demo records into the table.

USE [MYDB]

SET IDENTITY_INSERT [dbo].[Employee] ON

GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (1, N'Vinod', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (2, N'Manoj', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (3, N'Ansh', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (4, N'Ritesh', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (5, N'Vishwas', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (6, N'Ansh', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
SET IDENTITY_INSERT [dbo].[Employee] OFF
GO

Step 3 – Open Visual Studio and Create a ASP.NET MVC DisplayRecordsUsingEntityFramework as shown in the below image.

Display Records using Entity Framework

Step 4 – Create an Empty template and click OK.

Step 5 – First of all, we need to Install Entity Framework. Goto Tool > Library Package Manager > Manage NuGet Packages For Solutions..

Display Records using Entity Framework

Display Records using Entity Framework

Step 6 – Right Click on the Model folder and Create a class with the name Employee and write the following code in Employee class.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;


namespace DisplayRecrodsUsingEntitryFramework.Models
{
[Table("Employee")]
public class Employee
{
[Key]
public Int64 EmployeeID { get; set; }
public string EmployeeName { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
public string State { get; set; }
public string City { get; set; }
public string Status { get; set; }


}
}

Step 7 – Right Click on the Model Folder and Create a Class EmployeeDbContext and write the following code in EmployeeDbContext class.

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

namespace DisplayRecrodsUsingEntitryFramework.Models
{
public class EmployeeDbContext:DbContext
{
public DbSet<Employee> Employee { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<EmployeeDbContext>(null);
base.OnModelCreating(modelBuilder);
}
}
}

Step 9 – Add the following Connection String in web.config class with the name EmployeeDbContext.

<connectionStrings>
<add name="EmployeeDbContext" connectionString="data source=DESKTOP-9VC12LL\SQLEXPRESS;Initial Catalog=MYDB;integrated security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

Step 8 – Right Click on the Controller folder and Create a Controller with the name HomeController.

using DisplayRecordsUsingEntityFramework.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DisplayRecordsUsingEntityFramework.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/

EmployeeDbContext objEmployeeDbContext = new EmployeeDbContext();

public ActionResult Index()
{
List<Employee> lstEmployees = objEmployeeDbContext.Employee.ToList();
return View(lstEmployees);
}

}
}

Step 9 – Right Click on the Index Action method and add a View with the name Index.

Display Records using Entity Framework

Step 10 – Write the following code to Index.cshtml file.

@model IEnumerable<DisplayRecordsUsingEntityFramework.Models.Employee>

@{
ViewBag.Title = "Index";
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="~/Css/BootstrapTableCss.css" rel="stylesheet" />
<h2>Display Records using Entity Framework</h2>
<div class="container">
<div class="row">
 
<div id="no-more-tables">
<table class="col-md-12 table-bordered table-striped table-condensed cf">
<thead class="cf">
<tr>
<th>
@Html.DisplayNameFor(model => model.EmployeeName)
</th>
<th>
@Html.DisplayNameFor(model => model.Gender)
</th>
<th>
@Html.DisplayNameFor(model => model.Address)
</th>
<th>
@Html.DisplayNameFor(model => model.State)
</th>
<th>
@Html.DisplayNameFor(model => model.City)
</th>
<th>
@Html.DisplayNameFor(model => model.Status)
</th>
 
</tr>

</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td data-title="Employee Name">
@Html.DisplayFor(modelItem => item.EmployeeName)
</td>
<td data-title="Gender">
@Html.DisplayFor(modelItem => item.Gender)
</td>
<td data-title="Address">
@Html.DisplayFor(modelItem => item.Address)
</td>
<td data-title="State">
@Html.DisplayFor(modelItem => item.State)
</td>
<td data-title="City">
@Html.DisplayFor(modelItem => item.City)
</td>
<td data-title="Status">
@Html.DisplayFor(modelItem => item.Status)
</td>
 
</tr>
}
</tbody>
</table>
</div>
</div>
</div>

Run the Application. The output window should look like this.

Display Records using Entity Framework

View More:

Conclusion:

I hope you understand this tutorial. I would like to have your valuable comments, feedback and suggestions.

Thank You.

169 Comments

  • The very next time I read a blog, Hopefully it won’t fail me just as much as this one. After all, Yes, it was my choice to read, but I actually thought you would have something interesting to say. All I hear is a bunch of whining about something you could possibly fix if you weren’t too busy searching for attention.

  • I just want to tell you that I am just newbie to weblog and honestly enjoyed your website. Almost certainly I’m want to bookmark your site . You definitely come with good stories. Thanks a lot for sharing your webpage.

  • I simply want to mention I am just new to blogging and certainly enjoyed this blog. Very likely I’m going to bookmark your blog post . You really have good articles and reviews. Thank you for sharing your website.

  • Sapid Agency is a Search Engine Optimization company in New York City that provides SEO Services. Their proprietary SEO strategies help struggling websites and aspiring business owners to rank their websites higher in multiple search engines like Google , Yahoo and Bing. They provide local and gmb map ranking for businesses in NYC and many other local areas. Find more at https://www.sapidagency.com/ @ 145 E 57TH NEW YORK, NY 10022, USA, +1 971 341 5608 USA

  • An impressive share! I’ve just forwarded this onto a colleague who was conducting a little research on this. And he actually ordered me dinner simply because I found it for him… lol. So allow me to reword this…. Thank YOU for the meal!! But yeah, thanx for spending the time to talk about this issue here on your blog.

  • I blog quite often and I truly appreciate your content. The article has truly peaked my interest. I will book mark your website and keep checking for new information about once per week. I subscribed to your Feed as well.

  • I really love your website.. Pleasant colors & theme. Did you create this site yourself? Please reply back as I’m planning to create my own personal site and would love to know where you got this from or what the theme is named. Cheers!

  • I have realized some important things through your site post. One other stuff I would like to state is that there are various games on the market designed specifically for toddler age kids. They incorporate pattern identification, colors, wildlife, and styles. These usually focus on familiarization in lieu of memorization. This will keep little ones occupied without experiencing like they are learning. Thanks

  • An outstanding share! I’ve just forwarded this onto a co-worker who has been conducting a little research on this. And he in fact bought me dinner because I found it for him… lol. So let me reword this…. Thank YOU for the meal!! But yeah, thanks for spending some time to talk about this issue here on your blog.

  • This is a topic that is near to my heart… Best wishes! Exactly where can I find the contact details for questions?

  • Sapid Agency is a Search Engine Optimization company in New York City that provides SEO Services. Their proprietary SEO strategies help struggling websites and aspiring business owners to rank their websites higher in multiple search engines like Google , Yahoo and Bing. They provide local and gmb map ranking for businesses in NYC and many other local areas. Find more at https://www.sapidagency.com/ @ 145 E 57TH NEW YORK, NY 10022, USA, +1 971 341 5608 USA

  • Way cool! Some very valid points! I appreciate you penning this write-up and also the rest of the site is really good.

  • I really love your website.. Great colors & theme. Did you create this web site yourself? Please reply back as I’m attempting to create my own personal website and want to find out where you got this from or what the theme is called. Appreciate it.

  • After I originally commented I seem to have clicked the -Notify me when new comments are added- checkbox and from now on whenever a comment is added I receive four emails with the exact same comment. Is there a means you can remove me from that service? Cheers.

  • I really have to tell you that I am new to wordpress blogging and really loved your site. Very likely I am going to store your blog post . You undoubtedly have impressive article materials. Get Pleasure From it for share-out with us your very own web article

  • I really love your website.. Very nice colors & theme. Did you make this web site yourself? Please reply back as I’m attempting to create my own website and want to learn where you got this from or just what the theme is named. Many thanks.

  • Only a smiling visitant here to share the love (:, btw great design. “Justice is always violent to the party offending, for every man is innocent in his own eyes.” by Daniel Defoe.

  • Great article! We are linking to this particularly great post on our site. Keep up the good writing.

  • I do agree with all of the concepts you’ve presented in your post. They are really convincing and can definitely work. Nonetheless, the posts are too quick for beginners. May just you please lengthen them a little from next time? Thanks for the post.

  • I need to to thank you for this very good read!! I definitely loved every little bit of it. I have you saved as a favorite to check out new stuff you post…

  • This is the right blog for everyone who wishes to find out about this topic. You understand a whole lot its almost hard to argue with you (not that I actually will need to…HaHa). You definitely put a brand new spin on a subject that’s been written about for ages. Great stuff, just excellent.

  • Hello, I think your site could be having browser compatibility problems. Whenever I look at your web site in Safari, it looks fine however, when opening in IE, it has some overlapping issues. I merely wanted to provide you with a quick heads up! Apart from that, excellent site!

  • Hi, I do think this is an excellent site. I stumbledupon it 😉 I’m going to revisit once again since i have bookmarked it. Money and freedom is the best way to change, may you be rich and continue to help other people.

  • An intriguing discussion is definitely worth comment. I do believe that you should publish more on this subject matter, it may not be a taboo matter but typically people do not discuss such subjects. To the next! Cheers!

  • It is actually near not possible to come across well-advised americans on this niche, nevertheless you appear like you realize what you’re talking about! Thanks A Lot

  • Sapid Agency is a Search Engine Optimization company in New York City that provides SEO Services. Their proprietary SEO strategies help struggling websites and aspiring business owners to rank their websites higher in multiple search engines like Google , Yahoo and Bing. They provide local and gmb map ranking for businesses in NYC and many other local areas. Find more at https://www.sapidagency.com/ @ 145 E 57TH NEW YORK, NY 10022, USA, +1 971 341 5608 USA

  • MetroClick specializes in building completely interactive products like Photo Booth for rental or sale, Touch Screen Kiosks, Large Touch Screen Displays , Monitors, Digital Signages and experiences. With our own hardware production facility and in-house software development teams, we are able to achieve the highest level of customization and versatility for Photo Booths, Touch Screen Kiosks, Touch Screen Monitors and Digital Signage. Visit MetroClick in NYC at http://www.metroclick.com/ or , 121 Varick St, New York, NY 10013, +1 646-843-0888.

  • Spot on with this write-up, I truly feel this website needs a great deal more attention. I’ll probably be returning to see more, thanks for the info!

  • Your means of telling the whole thing in this paragraph is truly pleasant, all be capable of without difficulty be aware of it, Thanks a lot.|

  • I uncovered your blog site on google and also check a few of your very early blog posts. Continue to keep up the great operate. I simply additional up your RSS feed to my MSN Information Reader. Looking for ahead to learning more from you in the future!?

  • An fascinating discussion will probably be worth comment. I think that you ought to write much more about this topic, it will not become a taboo subject but usually everyone is too few to communicate on such topics. Yet another. Cheers

  • There are some intriguing times in this short article but I don?t recognize if I see all of them facility to heart. There is some legitimacy however I will take hold point of view until I explore it even more. Good write-up, many thanks and also we desire extra! Contributed to FeedBurner also

  • I was recommended this web site by my cousin. I’m not sure whether this post is written by him as nobody else know such detailed about my difficulty. You’re wonderful! Thanks!|

  • A fascinating discussion is worth remark. I assume that you ought to create extra on this subject, it could not be a taboo topic however normally people are not nearly enough to speak on such subjects. To the following. Thanks

  • I am typically to blog writing and i really appreciate your content. The article has really peaks my rate of interest. I am going to bookmark your website as well as keep looking for brand-new information.

  • Heya i am for the first time here. I came across this board and I find It truly useful & it helped me out much. I hope to give something back and help others like you helped me.|

  • Every weekend i used to pay a visit this web page, for the reason that i want enjoyment, since this this web site conations in fact pleasant funny material too.|

  • I am typically to blogging and also i truly appreciate your content. The write-up has really peaks my passion. I am going to bookmark your website as well as keep looking for new details.

  • I?m amazed, I must claim. Really hardly ever do I encounter a blog that?s both educative and also enjoyable, and also let me tell you, you have hit the nail on the head. Your concept is superior; the concern is something that inadequate individuals are speaking wisely around. I am really satisfied that I stumbled across this in my look for something connecting to this.

  • Heya there, just became familiar with your weblog through Bing, and found that it is very informative. I’ll like in the event you retain these.

  • I merely have to show you that I am new to blogging and thoroughly loved your report. Most likely I am going to remember your blog post . You really have impressive article content. Get Pleasure From it for swapping with us your web webpage

  • When I initially commented I clicked the -Alert me when new remarks are added- checkbox as well as now each time a comment is added I get 4 e-mails with the very same comment. Exists any way you can remove me from that solution? Many thanks!

  • Oh my benefits! an impressive article dude. Thanks However I am experiencing concern with ur rss. Don?t recognize why Incapable to sign up for it. Is there anyone getting identical rss problem? Any person that knows kindly react. Thnkx

  • Hi! I just would like to offer you a big thumbs up for your great info you’ve got here on this post. I am coming back to your site for more soon.|

  • Aw, this was a really nice message. In concept I want to put in creating similar to this in addition? taking time and also actual initiative to make a great short article? but what can I claim? I postpone alot and never seem to obtain something done.

  • There are definitely a lot of details like that to take into consideration. That is a great indicate raise. I offer the ideas above as general ideas but plainly there are inquiries like the one you bring up where one of the most crucial point will certainly be operating in honest good faith. I don?t know if best methods have actually arised around points like that, however I make certain that your task is plainly recognized as an up for grabs. Both young boys and also ladies really feel the effect of just a moment?s pleasure, for the rest of their lives.

  • It?s difficult to find well-informed individuals on this subject, but you seem like you understand what you?re discussing! Many thanks

  • Good blog post. I discover something more difficult on various blogs day-to-day. It will constantly be stimulating to review content from various other authors and exercise a something from their shop. I?d favor to use some with the material on my blog whether you don?t mind. Natually I?ll give you a web link on your web blog site. Thanks for sharing.

  • Howdy, There’s no doubt that your blog could possibly be having browser compatibility issues. When I look at your site in Safari, it looks fine however when opening in IE, it’s got some overlapping issues. I just wanted to give you a quick heads up! Besides that, wonderful blog.

  • You made some suitable factors there. I looked on the internet for the issue and found most individuals will certainly go along with with your site.

  • For latest news you have to pay a visit world-wide-web and on the web I found this web site as a best web page for most up-to-date updates.|

  • I?d need to check with you below. Which is not something I usually do! I appreciate reading an article that will certainly make individuals believe. Likewise, thanks for permitting me to comment!

  • I’m not that much of a internet reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your site to come back later. Cheers|

  • Oh my benefits! an outstanding write-up man. Thanks Nevertheless I am experiencing issue with ur rss. Don?t know why Incapable to subscribe to it. Exists anybody getting the same rss issue? Anybody that knows kindly react. Thnkx

  • After research study a few of the article on your website currently, and I really like your means of blog writing. I bookmarked it to my book mark internet site checklist as well as will certainly be checking back soon. Pls look into my web site also and let me recognize what you believe.

  • After study a few of the blog posts on your internet site now, and I truly like your means of blog writing. I bookmarked it to my book marking internet site list as well as will be checking back soon. Pls take a look at my web site also and let me recognize what you assume.

  • I simply want to tell you that I’m very new to blogs and honestly loved your web-site. Likely I’m planning to bookmark your blog post . You amazingly come with superb article content. Many thanks for sharing with us your blog.

  • I was extremely delighted to discover this web-site. I intended to thanks for your time for this wonderful read!! I absolutely taking pleasure in every bit of it and I have you bookmarked to have a look at brand-new stuff you blog post.

  • Hey are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and create my own. Do you require any coding knowledge to make your own blog? Any help would be really appreciated!|

  • cbd oil online yaa health store: cbd oil – cbd oil near me
    cbdoilforsalerate.com/ cbd oil for anxiety

  • There are some intriguing moments in this article however I don?t know if I see every one of them facility to heart. There is some legitimacy yet I will certainly hold point of view until I look into it further. Great short article, many thanks and we desire more! Added to FeedBurner too

  • Thank you for sharing your info. I really appreciate your efforts and I am waiting for your next post thank you once again.|

  • I?m satisfied, I have to claim. Truly hardly ever do I experience a blog that?s both informative as well as amusing, and let me tell you, you have hit the nail on the head. Your suggestion is impressive; the concern is something that not nearly enough people are speaking smartly around. I am very satisfied that I stumbled across this in my search for something associating with this.

  • I really like what you guys are usually up too. This kind of clever work and exposure! Keep up the amazing works guys I’ve included you guys to blogroll.|

  • I’m impressed, I have to admit. Seldom do I encounter a blog that’s both educative and entertaining, and without a doubt, you have hit the nail on the head. The problem is something that not enough people are speaking intelligently about. Now i’m very happy I came across this during my hunt for something regarding this.|

  • I was really pleased to find this web-site. I intended to thanks for your time for this remarkable read!! I certainly appreciating every little bit of it as well as I have you bookmarked to take a look at new stuff you article.

  • Excellent weblog here! Also your site so much up fast! What web host are you the use of? Can I get your associate link to your host? I desire my site loaded up as quickly as yours lol|

  • I simply want to tell you that I am just newbie to blogs and definitely liked you’re website. Likely I’m likely to bookmark your blog post . You definitely come with impressive stories. Thanks a bunch for sharing your blog.

  • I constantly spent my half an hour to read this webpage’s articles daily along with a cup of coffee.|

  • Excellent weblog right here! Additionally your site a lot up fast! What web host are you the usage of? Can I am getting your associate link to your host? I desire my web site loaded up as fast as yours lol|