工具:VS.net2013、EF6、MVC5、SQLServer2008
參考出處:
http://www.cnblogs.com/slark/p/mvc-5-get-started-create-project.html
http://www.cnblogs.com/miro/p/4288184.html
http://www.cnblogs.com/dotnetmvc/p/3732029.html
一、准備工作
在SqlServer上創建數據庫:Element
模擬兩個表並插入數據:SysUser(用戶表)、SysRole(角色表)
CREATE TABLE [dbo].[SysUser](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nchar](10) NOT NULL,
[RoleNum] [nchar](10) NOT NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[SysRole](
[ID] [int] IDENTITY(1,1) NOT NULL,
[RoleName] [nchar](10) NOT NULL,
[RoleNum] [nchar](10) NOT NULL
) ON [PRIMARY]
插入數據:





二、使用EF的Code First從原有數據庫中生成Models










三、根據Model生成Controller及View
在Controllers文件夾上右鍵--添加--控制器



四、利用ViewModel顯示多表聯合查詢

namespace MVCDemo.ViewModels
{
public class UserRole
{
public string userName { get; set; }
public string userRole { get; set; }
}
}
右鍵Controllers文件夾添加控制類,此類繼承於Controller類
using System;
using System.Collections.Generic;
using System.Linq; using System.Web;
using System.Web.Mvc; using System.Data.Entity;
using MVCDemo.ViewModels;
using MVCDemo.Models;
namespace MVCDemo.Controllers
{
public class UserRoleController : Controller
{
ElementModel db = new ElementModel();
public ActionResult Index()
{
var userRoleList = from uu in db.SysUsers
join ud in db.SysRoles on uu.RoleNum equals ud.RoleNum
where uu.ID == 1
select new UserRole {userName = uu.Name,userRole = ud.RoleName}
return View(userRoleList);
}
}
}
@model IEnumerable<MVCDemo.ViewModels.UserRole>
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model=>model.userName)
</th>
<th>
@Html.DisplayNameFor(model => model.userRole)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.userName)
</td>
<td>
@Html.DisplayFor(modelItem => item.userRole)
</td>
</tr>
}
</table>