MVC5 + EF6 simple example --- take the two tables of the original SQLServer database for joint query as an example, mvc5ef6
Tools: VS. net2013, EF6, MVC5, and SQLServer2008
Reference:
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
I. Preparations
Create a database on SqlServer: Element
Simulate two tables and insert data: SysUser and 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]
Insert data:
Http://www.cnblogs.com/dotnetmvc/p/3644980.html right-click the Controllers folder -- add -- Controller
Namespace MVCDemo. ViewModels
{
Public class UserRole
{
Public string userName {get; set ;}
Public string userRole {get; set ;}
}
}
Right-click the Controllers folder to add a control class. This class inherits from the Controller class.
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 );
}
}
}
Right-click the Views folder and create a new UserRole folder. Right-click the UserRole folder and add the Index. cshtml of the MVC5 view page with a layout. Add the following code:
@ 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>