有二三年沒(méi)寫(xiě)代碼了,**內(nèi)的工作就是這樣,容易廢人!看到園子里這么多大俠朝氣蓬勃的,我想也要學(xué)點(diǎn)東西并和大家分享,共同進(jìn)步!快樂(lè)每一天,進(jìn)步每一天!言歸正傳!
通過(guò)最近一段時(shí)間對(duì)MVC5、EF6的學(xué)習(xí),可以簡(jiǎn)單的做一個(gè)小例子,其中涉及到EF讀取已有數(shù)據(jù)庫(kù)中的數(shù)據(jù),并對(duì)兩個(gè)表進(jìn)行聯(lián)合查詢(xún),顯示數(shù)據(jù)。
工具:VS.net2013、EF6、MVC5、SQLServer2008
參考出處:
http://www.companysz.com/slark/p/mvc-5-get-started-create-PRoject.html
http://www.companysz.com/miro/p/4288184.html
http://www.companysz.com/dotnetmvc/p/3732029.html
在SqlServer上創(chuàng)建數(shù)據(jù)庫(kù):Element
模擬兩個(gè)表并插入數(shù)據(jù):SysUser(用戶(hù)表)、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]
插入數(shù)據(jù):
在Controllers文件夾上右鍵--添加--控制器
namespace MVCDemo.ViewModels{ public class UserRole { public string userName { get; set; } public string userRole { get; set; } }}
右鍵Controllers文件夾添加控制類(lèi),此類(lèi)繼承于Controller類(lèi)
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視圖頁(yè)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>
運(yùn)行生成的界面如下:新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注