To create a Student controller, right-click the Controllers folder in Solution Explorer, select Add, and then
click Controller. In the Add Controller dialog box, make the following selections and then click Add:
Controller name: StudentController.
- Template: Controller with read/write actions and views, using Entity Framework. (The default.)
- Model class: Student (MVC3EntityFrameworkDemo.Models). (If you don't see this option in the drop-down list, build the project and try again.)
- Data context class: SchoolContext (MVC3EntityFrameworkDemo.Models).
- Views: Razor (CSHTML). (The default.)
Open the Controllers\StudentController.cs file. You see a class variable has been created that instantiates a database context object:
private SchoolContext db =new SchoolContext();
The Index action method gets a list of students from the Students property of the database context instance:
public View Result Index()
{
return View(db.Students.ToList());
}
The automatic scaffolding has also created a set of Student views. To customize the default headings and column order in the Index view, open Views\Student\Index.cshtml and replace the existing code with the following code:
@modelIEnumerable<ContosoUniversity.Models.Student>
@{
ViewBag.Title="Students";
}
<h2>Students</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th></th>
<th>Last Name</th>
<th>FirstName</th>
<th>Enrollment Date</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.StudentID }) |
@Html.ActionLink("Details", "Details", new { id=item.StudentID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.StudentID })
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstMidName)
</td>
<td>
@Html.DisplayFor(modelItem => item.EnrollmentDate)
</td>
</tr>
}
</table>
Run the site, click the Students tab, and you see a list of students.
Close the browser. In Solution Explorer, select the MVC3EntityFrameworkDemo project (make sure the project and not the solution is selected). Click Show all Files if you aren't already in that mode. Click Refresh and then expand the App_Data folder to see the School.sdf file.
Double-click School.sdf to open Server Explorer. Then expand the Tables folder to see the tables that have been created in the database.
Getting Started with Entity Framework Code First
Introduction to POCO classes in Entity Framework
Create First MVC application in Visual Studio 2010
Creating the Entity Framework Data Model in Visual Studio
Create classes for each entity using Entity Framework
Create the Database Context using Entity Framework
Setting the Connection String in MVC Asp.Net Application
Creating a Controller and Views in MVC application
0 comments:
Post a Comment