Asp.net MVC4 使用EF實現數據庫的增刪改查


EF的使用
步驟:
(1)將EF添加到項目:在Model右擊添加新建項
找到ADO.NET實體數據模型,接着。。。
(2)實現 數據庫的增刪改查
 
 
 
查詢
(因為在Model中已經添加EF實體了,所以就可以在Controller中進行有關的數據庫操作)
<<controller>>
       //數據上下文對象
        OrderDBEntities db = new OrderDBEntities();
        public ActionResult Index() {
            //使用SQO(標准查詢運算符),查詢
            //實際返回的是IQueryable 接口的之類對象
            //IQueryable<Models.Customer> query = db.Customers.Where(d => d.Address == "111");
            //這樣轉有可能報異常 EnumerableQuery<Models.Customer> query = (EnumerableQuery<Models.Customer>)db.Customers.Where(d => d.Address == "111");
            //DbQuery 支持延遲加載,就是只有使用到數據的時候,才去查詢數據庫
            
            //DbQuery<Models.Customer> query = db.Customers.Where(d => d.Address == "111") as DbQuery<Models.Customer>;
            //List<Models.Customer> list = query.ToList();
            //也可以這樣
            // List<Models.Customer> list = db.Customers.Where(d => d.Address == "111").ToList();
            //用第二種方式:使用Linq語句,該語法只是給程序員用的,.net編譯器會在編譯程序集的時候把它轉化為SQO
            //IQueryable<Models.Customer> query = from d in db.Customers where d.Address == "111" select d;
            //List<Models.Customer> list = (from d in db.Customers where d.Address == "111" select d).ToList();
            List<Models.Customer> list = (from d in db.Customers select d).ToList();
           //使用ViewData將數據傳給View
            ViewData["DataList"] = list;
            return View();
        }
 
<<View>>
<body>
    <table border="1">       
   <!--要取到數據就直接@對應的變量 這樣就可以了(導入命名空間也是一個道理)-->
    @foreach (Customer a in ViewData["DataList"] as List<Customer>) 
    {
        <tr>
        <td>@a.Address</td>
        <td>@a.CustomerName</td>
        <td><a href="/home/del/@a.CustomerNo">刪除</a>
            <a href="/home/modify/@a.CustomerNo">修改</a>
        </td>
        </tr>
    }     
     </table>
</body>
 
 
刪除:
<<Controller>>
 
public ActionResult Del(string id) //這個id是通過超鏈接帶過來的
        {
            try
            {
                //需要一個實體對象參數
                //db.Customers.Remove(new Customer() {CustomerNo = id });
                //1,創建要刪除的對象
                Customer modelDel = new Customer() { CustomerNo = id };
                //2,將對象添加到EF管理容器中
                db.Customers.Attach(modelDel);
                //3,修改對象的包裝類對象標識為刪除狀態
                db.Customers.Remove(modelDel);
                //4,更新到數據庫
                db.SaveChanges();
                //5,更新成功,則命令流浪器重定向 到 /Home/Index 方法
                return RedirectToAction("Index", "Home");
            }
            catch (Exception )
            {   
                //指定對應跳轉的視圖Test下的Test.cs html文件
               return RedirectToAction("Test", "Test");
               //return Content("刪除失敗" + ex.Message);
            }
        }
<<View>>
刪除哪有什么視圖,成功失敗頁面不給出了
 
 
修改
在視圖里面肯定又個修改連接,點擊跳轉到對應的頁面,並將參數傳遞給對應的函數
<<View>>
<body>
    <table border="1">
        
   <!--要取到數據就直接@對應的變量 這樣就可以了(導入命名空間也是一個道理)-->
    @foreach (Customer a in ViewData["DataList"] as List<Customer>) 
    {
        <tr>
        <td>@a.Address</td>
        <td>@a.CustomerName</td>
        <td><a href="/home/del/@a.CustomerNo">刪除</a>
            <a href="/home/modify/@a.CustomerNo">修改</a>
        </td>
        </tr>
    }     
     </table>
</body>
//調用到控制器中的modify方法,並以表單的形式顯示相應的頁面
<<Controller>>
 
 
[HttpGet] //加上這個 只要是超鏈接發送過來的就調用這個
        public ActionResult Modify(string id)
        {
            Customer art = (from d in db.Customers where d.Address == "111" select d).FirstOrDefault();
            //將數據傳遞給視圖:用ViewBag viewData 使用view的構造函數
            return View(art);
        }
<<View>>
 
 
<body>
    @using (Html.BeginForm("Modify", "Home", FormMethod.Post)) 
    {
        <table>
            <tr>
                <td colspan="2">修改</td>
            </tr>
            <tr>
                <td>標題:@Html.HiddenFor(a=>a.CustomerNo)</td>
                @*<td>@Html.TextBox("textName",(object)Model.CustomerNo)</td>*@
                <!--使用htmlHelper的強類型方法,直接從Model中根據CustoomerNo生成文本框-->
                <td>@Html.TextBoxFor(a =>a.CustomerNo)</td>
                <td>@Html.TextBoxFor(a =>a.CustomerName)</td>
                <td><input type="submit" value="確定修改" />@Html.ActionLink("返回","index","home")</td>
            </tr>
        </table>
    }
</body>
當用戶點擊修改的時候又將數據以Post方式發送給Home控制器中的Modify函數進行處理
<<Controller>>
 
[HttpPost] //表單提交過來的就調用這個方法
        public ActionResult Modify(Customer model)
        {
            try
            {
                //1,將實體對象加入EF對象容器中,並獲取偽包裝類對象
                DbEntityEntry<Customer> entry = db.Entry<Customer>(model);
                //2,將偽包裝類對象的狀態設置為unchanged
                entry.State = System.Data.EntityState.Unchanged;
                //3,設置被改變的屬性
                entry.Property(a => a.CustomerName).IsModified = true;
                //4,提交到數據庫 完成修改
                db.SaveChanges();
                return RedirectToAction("Index", "Home");
            }
            catch (Exception)
            {
                return RedirectToAction("Test", "Test");
            }
        }
 
 
補充:MVC中頁面之間的跳轉是通過MapRouter
代碼如下
routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
 );

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM