Click here to Skip to main content
15,884,032 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have an Student table in sql. I want to show data of this table in view using Entity framework data model.
I am fresher in MVC. Can anyone help me.
Thank you
Posted

Hi,

Try to use EF code first, it would be much simpler to understand it.
1. Create your solution(ASP>MVC )
2. Download NuGet package in package manager console write the next:
- Install-Package EntityFramework -Version 4.3.1

3) Create you database context class, for example:
C#
public calss StudentContext:DbContext
{
  public StudentContext():base("name=ConStringName"){}
  //where ConStringName -> key of your connection string in config file.

  public DbSet<student> Students{get;set;}
}</student>


4) Create Student Entity ->
C#
public class Student
{
 [System.ComponentModel.DataAnnotations.Key] //do not forget to add reference to System.ComponentModel.DataAnnotations.dll
 public int Id{get;set;}
 [Required()]
 public string Name {get;set;}
//other stuff was ommited for brevity!!
}


5) Create StudentController module and implement Index method in it:
C#
public class StudentController:Controller
{
  public ActionResult Index()
  {
   using(var context=new StudentContext())
   {
    return View(context.Students.AsEnumerable());
   }
  } 
}


6) the last one all you nedd is to create Index view:
HTML
@model IEnumerable<student>
@{
 ViewBag.Title="Student index page"
}
<ul>
 @{
   foreach(var student in Model)
   <li>@student.Name</li>
  }
</ul>


Hope this will help you!!
 
Share this answer
 
v2
Comments
Member 9583779 24-Dec-12 0:53am    
But i have an existing database and i want it to be done with Database First ..
I don't want that code create my database. I have existing database.
Please Help me.
Thank you
Oleksandr Kulchytskyi 24-Dec-12 3:30am    
No problem , make a reverse engineering from existing DB you can successfully replicate to code-first model, just look at this link -> http://thedatafarm.com/blog/data-access/quick-look-at-reverse-engineer-db-into-code-first-classes/

And the rest still remains the same as i wrote above!
you can add entity model (edmx) in your project and then you can bind the table with view using that model.
 
Share this answer
 
Comments
Member 9583779 24-Dec-12 3:08am    
i have added edmx in my project and then attached database table with this edmx.
what should be the next step. I want to display data of this table

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900