1. 程式人生 > >Asp.Net+ EntityFramework+MVC

Asp.Net+ EntityFramework+MVC

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&lt;T&gt; 屬性的 .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