ASP.NET MVC 5 + Entity Framework – Data Access Layer 方法
( Project : SoccerMVCDAL ) \DAL\PlayerDAL.cs |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoccerMVCDAL.DAL { public class PlayerDAL { SoccerEntities entity; public Player() { entity = new SoccerEntities(); } public List<PLAYER> getAllPlayer() { return entity.PLAYERs.ToList(); } public PLAYER getPlayerByPlayID(int PlayerID) { PLAYER player = entity.PLAYERs.Where(x=>x.PLAYER_ID == PlayerID).FirstOrDefault(); if(player != null) return player; else return null; } public List<PLAYER> getPlayerByNation(int NationID) { return entity.PLAYERs.Where(x => x.PLAYER_NATION == NationID).ToList(); } public List<PLAYER> getPlayerByTeam(int TeamID) { return entity.PLAYERs.Where(x => x.PLAYER_TEAM == TeamID).ToList(); } public List<PLAYER> getPlayerByPosition(int PositionID) { return entity.PLAYERs.Where(x => x.PLAYER_POSITION == PositionID).ToList(); } } } |
( Project : SoccerMVCWebApp ) web.conf |
<configuration> <connectionStrings> <add name="SoccerEntities" connectionString="… …" providerName="System.Data.EntityClient" /> </connectionStrings> … … </configuration> |
( Project : SoccerMVCWebApp ) \Controllers\PlayerController.cs |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using SoccerMVCDAL.DAL; namespace SoccerMVCWebApp.Controllers { public class PlayerController : Controller { PlayerDAL DAL; public PlayerController() { DAL = new PlayerDAL(); } public ActionResult Index() { return View(DAL.getAllPlayer()); } public ActionResult Position(int? ID) { if(ID.HasValue) return View("Index", DAL.getPlayerByPosition(ID.Value)); else return View("Index", DAL.getAllPlayer()); } public ActionResult Nation(int? ID) { if (ID.HasValue) return View("Index", DAL.getPlayerByNation(ID.Value)); else return View("Index", DAL.getAllPlayer()); } public ActionResult Team(int? ID) { if (ID.HasValue) return View("Index", DAL.getPlayerByTeam(ID.Value)); else return View("Index", DAL.getAllPlayer()); } } } |
( Project : SoccerMVCWebApp ) \Views\Player\index.cshtml |
@model List<SoccerMVCDAL.PLAYER> <style> table tr td{ padding-right:14px; } </style> <table border="0" cellpadding="0" cellspacing="0" cellspacing="0"> @{ foreach (SoccerMVCDAL.PLAYER item in Model) { <tr> <td>@(item.PLAYER_ID)</td> <td>@(item.PLAYER_NAME)</td> <td>@(item.PLAYER_NATION)</td> <td>@(item.PLAYER_POSITION)</td> <td>@(item.PLAYER_TEAM)</td> <td>@(item.PLAYER_BIRTHDAY.Value.ToShortDateString())</td> </tr> } } </table> |