Asp.Net+ EntityFramework+MVC
程序员文章站
2022-07-14 11:26:09
...
using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.ComponentModel; namespace UI.Models { /// <summary> /// 远程验证 /// [Remote("CheckEmail", "Register", ErrorMessage = "此邮箱已存在")] /// </summary> public class User { public int id { get; set; } [DisplayName("姓名")] [Required(ErrorMessage = "姓名不能为空")] [StringLength(1000, ErrorMessage = "长度在5-1000", MinimumLength = 5)] public string UserName { get; set; } [Required(ErrorMessage = "密码不能为空")] [StringLength(1000, ErrorMessage = "长度在6-20", MinimumLength = 6)] public string PassWord { get; set; } [Required(ErrorMessage = "地址不能为空")] [StringLength(1000, ErrorMessage = "长度在5个字符", MinimumLength = 5)] public string Address { get; set; } } }
using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using UI.Entity_Framework; using System.Collections; using UI.Models; namespace UI.Controllers { /// <summary> /// http://www.jquery001.com/asp.net-mvc3-instance-router-and-multiple-data-model-in-one-view.html /// </summary> public class UserController : Controller { UsersEntities entity = new UsersEntities(); public ActionResult User() { //android.Article,就是通过ObjectSet属性 //List<Article> //var article = android.Article.ToList(); //使用 Linq 查询 var result = from a in entity.Users select a; //ViewResult//这个View和Spring的ModelAndView差不多. return View(result); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.Routing; namespace UI.InterFace { public interface IRouteHandler { IHttpHandler GetHttpHandler(RequestContext requestContext); } }
//------------------------------------------------------------------------------ // <auto-generated> // 此代码是根据模板生成的。 // // 手动更改此文件可能会导致应用程序中发生异常行为。 // 如果重新生成代码,则将覆盖对此文件的手动更改。 // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Data.Objects; using System.Data.Objects.DataClasses; using System.Data.EntityClient; using System.ComponentModel; using System.Xml.Serialization; using System.Runtime.Serialization; [assembly: EdmSchemaAttribute()] namespace UI.Entity_Framework { #region 上下文 /// <summary> /// 没有元数据文档可用。 /// </summary> public partial class UsersEntities : ObjectContext { //public ObjectSet<Users> _user { get; set; } #region 构造函数 /// <summary> /// 请使用应用程序配置文件的“UsersEntities”部分中的连接字符串初始化新 UsersEntities 对象。 /// </summary> public UsersEntities() : base("name=UsersEntities", "UsersEntities") { this.ContextOptions.LazyLoadingEnabled = true; OnContextCreated(); } /// <summary> /// 初始化新的 UsersEntities 对象。 /// </summary> public UsersEntities(string connectionString) : base(connectionString, "UsersEntities") { this.ContextOptions.LazyLoadingEnabled = true; OnContextCreated(); } /// <summary> /// 初始化新的 UsersEntities 对象。 /// </summary> public UsersEntities(EntityConnection connection) : base(connection, "UsersEntities") { this.ContextOptions.LazyLoadingEnabled = true; OnContextCreated(); } #endregion #region 分部方法 partial void OnContextCreated(); #endregion #region ObjectSet 属性 /// <summary> /// 没有元数据文档可用。 /// </summary> public ObjectSet<Users> Users { get { if ((_Users == null)) { _Users = base.CreateObjectSet<Users>("Users"); } return _Users; } } private ObjectSet<Users> _Users; #endregion #region AddTo 方法 /// <summary> /// 用于向 Users EntitySet 添加新对象的方法,已弃用。请考虑改用关联的 ObjectSet<T> 属性的 .Add 方法。 /// </summary> public void AddToUsers(Users users) { base.AddObject("Users", users); } #endregion } #endregion #region 实体 /// <summary> /// 没有元数据文档可用。 /// </summary> [EdmEntityTypeAttribute(NamespaceName="UsersModel", Name="Users")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Users : EntityObject { #region 工厂方法 /// <summary> /// 创建新的 Users 对象。 /// </summary> /// <param name="id">Id 属性的初始值。</param> /// <param name="passWord">PassWord 属性的初始值。</param> public static Users CreateUsers(global::System.Int32 id, global::System.String passWord) { Users users = new Users(); users.Id = id; users.PassWord = passWord; return users; } #endregion #region 基元属性 /// <summary> /// 没有元数据文档可用。 /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Id { get { return _Id; } set { if (_Id != value) { OnIdChanging(value); ReportPropertyChanging("Id"); _Id = StructuralObject.SetValidValue(value); ReportPropertyChanged("Id"); OnIdChanged(); } } } private global::System.Int32 _Id; partial void OnIdChanging(global::System.Int32 value); partial void OnIdChanged(); /// <summary> /// 没有元数据文档可用。 /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public global::System.String UserName { get { return _UserName; } set { OnUserNameChanging(value); ReportPropertyChanging("UserName"); _UserName = StructuralObject.SetValidValue(value, true); ReportPropertyChanged("UserName"); OnUserNameChanged(); } } private global::System.String _UserName; partial void OnUserNameChanging(global::System.String value); partial void OnUserNameChanged(); /// <summary> /// 没有元数据文档可用。 /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String PassWord { get { return _PassWord; } set { OnPassWordChanging(value); ReportPropertyChanging("PassWord"); _PassWord = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("PassWord"); OnPassWordChanged(); } } private global::System.String _PassWord; partial void OnPassWordChanging(global::System.String value); partial void OnPassWordChanged(); /// <summary> /// 没有元数据文档可用。 /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public global::System.String Address { get { return _Address; } set { OnAddressChanging(value); ReportPropertyChanging("Address"); _Address = StructuralObject.SetValidValue(value, true); ReportPropertyChanged("Address"); OnAddressChanged(); } } private global::System.String _Address; partial void OnAddressChanging(global::System.String value); partial void OnAddressChanged(); #endregion } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using UI.Entity_Framework; namespace UI.Controllers { /// <summary> /// <Author>梁继龙</Author> /// <Language>C Sharp</Language> /// <Description>ASP.NET MVC3+LINQ+Entity FrameWork</Description> /// <Date>2012/18</Date> /// 一、默认情况下Action上标上重写的ActionAttributeFilter注解后, /// 在Controller上也标上注解,但它只有Action上的标签起作用了 /// 二、我们只需在DemoActionAttributeFilter类的定义上打上标记 /// [AttributeUsage(AttributeTargets.All,AllowMultiple = true)] /// 这样让其成为可以多次执行的Action /// </summary> //[IActionFilterAttribute(Message = "IndexController")] public class IndexController : Controller { /// <summary> /// 定向 /// return RedirectPermanent("index"); /// return RedirectToActionPermanent("index"); /// return RedirectToRoutePermanent("index"); /// </summary> //创建一个Entity FrameWork对象 private UsersEntities entities = new UsersEntities(); //[IActionFilterAttribute(Message = "action")] public ActionResult Index() { //return StartController(); return FindUser(); } /// <summary> /// 开始的MVC3的测试 /// </summary> /// <returns></returns> private ActionResult StartController() { this.ControllerContext.HttpContext.Response.Write(@"<br />Action execute"); return View(); } /// <summary> /// 查询所有用户 /// </summary> /// <returns></returns> public ActionResult FindUser() { //使用 Linq 查询 from in select并不是数据库的SQL关键字 var result = from u in entities.Users select u; //ViewResult return View(result); } /// <summary> /// 创建用户 /// </summary> /// <returns></returns> [HttpPost]//注解 以post提交 public ActionResult CreateUser(Users user) { if (ModelState.IsValid) { entities.AddObject("User", user); //将所有更新保存到数据源并重置对象上下文中的更改跟踪,保存并改变数据库表的状态 entities.SaveChanges(); return RedirectToAction("../Index"); } else { return View(user); } } /// <summary> /// 编辑/修改 /// </summary> /// <param name="id"></param> /// <param name="collection"></param> /// <returns></returns> [HttpPost] public ActionResult Edit(int id, FormCollection collection) { try { var message = entities.Users.Single(edit => edit.Id == id); UpdateModel(message); entities.SaveChanges(); return RedirectToAction("Index");//返回到列表 } catch { return View(); } } /// <summary> /// 删除 /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpPost] public ActionResult Delete(int id) { try { var contact = entities.Users.Single(del => del.Id == id); entities.DeleteObject(contact); entities.SaveChanges(); return RedirectToAction("../Delete"); } catch (Exception) { throw; } } } }
using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using UI.Controllers; namespace UI { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Index", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } /// <summary> /// 注册路由 /// </summary> protected void Application_Start() { AreaRegistration.RegisterAllAreas(); //GlobalFilters.Filters.Add(new IActionFilterAttribute() { Message = "Gloable" });//配置公共的方法每个Action都执行 RegisterGlobalFilters(GlobalFilters.Filters);//注册全局过滤 RegisterRoutes(RouteTable.Routes);//注册路由RouteTable } } }
@model IEnumerable<UI.Entity_Framework.Users> @{ // ViewBag.Title = "Index"; //在asp mvc的cshtml文件里面的注释为 @**@ } <h2> <h1> <div align="center"> <table border=1> <tr > <td colspan="4" style="color:red" align=center> 运行的结果如下 </td> </tr> <tr> <td colspan="4" style="color:red"> ASP.NET MVC3 +FrameWork+Linq </td> </tr> <tr> <td>ID</td> <td>UserName</td> <td>Address</td> </tr> @foreach (var item in Model) { <tr> <td>@item.Id</td> <td>@item.UserName</td> <td>@item.Address</td> <td> @Html.ActionLink("添加", "Create", new { id = item.Id }) | @Html.ActionLink("修改", "Edit", new { id = item.Id }) | @Html.ActionLink("删除", "Delete", new { id = item.Id }) </td> </tr> } </table> <br /> </div>
@model UI.Entity_Framework.Users <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>Users</legend> <div class="editor-label"> @Html.LabelFor(model => model.UserName) </div> <div class="editor-field"> @Html.EditorFor(model => model.UserName) @Html.ValidationMessageFor(model => model.UserName) </div> <div class="editor-label"> @Html.LabelFor(model => model.PassWord) </div> <div class="editor-field"> @Html.EditorFor(model => model.PassWord) @Html.ValidationMessageFor(model => model.PassWord) </div> <div class="editor-label"> @Html.LabelFor(model => model.Address) </div> <div class="editor-field"> @Html.EditorFor(model => model.Address) @Html.ValidationMessageFor(model => model.Address) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div>
cshtml语法不在多描述,毕竟3年前的例子!现在的asp发展什么程度也不是很清楚,从事java开发之后都没安装过visual_studio去玩过c sharp语言,代码在网盘上面.
源代码:链接: http://pan.baidu.com/s/1bnUPxSj 密码: 9775