出处:http://www.cnblogs.com/lukun/archive/2011/08/15/2133477.html
1. 创建表
create table Department
(
DepartmentId int,
DepartNo varchar(200) primary key,
DepartName varchar(200),
ParentID int,
Remark text
)
create table Employee
(
EmployeeNo varchar(20),
EmployeeName varchar(100),
Sex char(2),
Birthday datetime,
Marital varchar(10),
DepartmentID int
)
insert into Department values(1,'1','Business1',0,'No')
insert into Department values(2,'2','Business2',1,'No')
insert into Department values(3,'3','Business3',2,'No')
insert into Department values(4,'4','Business4',2,'No')
insert into Department values(5,'5','Business5',2,'No')
insert into Department values(6,'6','Business6',2,'No')
insert into Department values(7,'7','Business7',2,'No')
insert into Department values(8,'8','Business8',2,'No')
insert into Department values(9,'9','Business9',2,'No')
insert into Employee values('1001','name1','1','1988-08-31','no',1)
insert into Employee values('1002','name2','1','1988-08-31','no',2)
insert into Employee values('1003','name3','1','1988-08-31','no',1)
insert into Employee values('1004','name4','1','1988-08-31','no',1)
insert into Employee values('1005','name5','1','1988-08-31','no',1)
insert into Employee values('1006','name6','1','1988-08-31','no',1)
insert into Employee values('1007','name7','1','1988-08-31','no',1)
insert into Employee values('1008','name8','1','1988-08-31','no',1)
insert into Employee values('1009','name9','1','1988-08-31','no',1)
2. 选择空白解决方案,视图引擎Razor
3. 添加Model(Model.dbml)
4. 创建BaseController基类,代码如下:
public class BaseController : Controller
{
//
// GET: /Base/
private ModelDataContext _DataContext = null;
protected ModelDataContext DataContext
{
// AssociateWith让你能够事先对EntitySet关联设置过滤条件
//LoadWith让你能够设置某些EntitySets为主动加载(eager loading),从而减少连接数据库的次数
get
{
if (_DataContext == null)
_DataContext = new ModelDataContext();
var options = new DataLoadOptions();
options.LoadWith<Employee>(p => p.EmployeeNo);
_DataContext.LoadOptions = options;
return _DataContext;
}
}
}
5. 创建EmployeeController,代码如下:
public class EmployeeController : BaseController
{
//
// GET: /Employee/
public ActionResult Index()
{
var list = this.DataContext.Employees;
return View(list);
}
}
6. 添加视图页面(右键添加):
@model IEnumerable<MvcApplication3.Models.Employee>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
Member List</h2>
<table border="1" width="100%" style="text-align: center; border-collapse: collapse">
<tr>
<th>
编号
</th>
<th>
姓名
</th>
<th>
性别
</th>
<th>
生日
</th>
<th>
是否婚配
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@item.EmployeeNo
</td>
<td>@item.EmployeeName
</td>
<td>
@if (item.Sex == "1")
{
@:@("Male")
}
@if (item.Sex != "1")
{
@:@("falmale")
}
</td>
<td>@string.Format("{0:yyyy-MM-dd}", item.Birthday)
</td>
<td>
@if (item.Marital == "1")
{
@:@("YES")
}
@if (item.Marital != "1")
{
@:@("No")
}
</td>
</tr>
}
</table>
7. 修改路由Global.asax为Employee