有二三年沒寫代碼了,**內的工作就是這樣,容易廢人!看到園子里這么多大俠朝氣蓬勃的,我想也要學點東西并和大家分享,共同進步!快樂每一天,進步每一天!言歸正傳!
通過最近一段時間對MVC5、EF6的學習,可以簡單的做一個小例子,其中涉及到EF讀取已有數據庫中的數據,并對兩個表進行聯合查詢,顯示數據。
工具:VS.net2013、EF6、MVC5、SQLServer2008
參考出處:
http://www.49028c.com/slark/p/mvc-5-get-started-create-PRoject.html
http://www.49028c.com/miro/p/4288184.html
http://www.49028c.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]
插入數據:
在Controllers文件夾上右鍵--添加--控制器
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);
}
}
}
右鍵Views文件夾,新建UserRole文件夾;右鍵UserRole文件夾,添加--帶有布局的MVC5視圖頁Index.cshtml,添加代碼如下:@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>
運行生成的界面如下:新聞熱點
疑難解答