> For the complete documentation index, see [llms.txt](https://johch3n611u.gitbook.io/c50108/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://johch3n611u.gitbook.io/c50108/ju-li-cheng-bei/201904/untitled-12.md).

# 2019/0430/資料庫設計應用效能調教\_SQL all end\&ASP.NET\_MVC\_Controller單元\_純C無V無M操作/簡單複雜繫結

\#資料庫設計與應用

\##交易處理

有些東西跳過沒講

可以看這個

{% embed url="<http://cilab.csie.ncu.edu.tw/students/xiang/course_972/ES750/ES750-14.ppt>" %}

![](/files/-LdhbYcjRSVeDRrH1nsq)

![](/files/-LdhbiNeK4Jetpur77KW)

### 交易

只有兩種可能性成功或失敗

且是

一筆一筆交易的互相較不干涉

唯一有錯的是明細關聯資料錯誤一筆就會影響另外一筆 ( 參考完整性遺失

必須寫程式說明資料為關聯同一筆一起更新一起刪除

![](/files/-LdhbrgSRRzQNMkzhnBx)

### 交易生命週期

![](/files/-LdhbxRpauOUcnjr_wRk)

保證在後面過程當中 一但有錯誤就 roll back 回暫存資料

![](/files/-Ldhc6EBQVFa8OrURcN6)

部分認可交易已到 trigger

![](/files/-LdhcCfkr0PuXsI5Evea)

考資料庫通常會考以下&#x20;

### acid 四大特性

![](/files/-LdhcIt1QrFJSnIp_DyO)

1.邏輯概念當作一筆交易，而不是交易的數量或筆數

2.實體 值域 參考 完整性

3.避免同時一堆人在存取某一筆資料時發生的錯誤 ( 資料庫系統本身會處理

![](/files/-LdhcYRHp075GD9ZVf86)

DNMS狀態過了通常就自動COMMIT但也可以手動指令

#### ###交易模式範例

![](/files/-LdhcgW2s_GiK9OdHDmn)

![](/files/-LdhcklJHhQLIJyPFvZY)

強迫 參考完整性 COUSTRINT FK錯誤 因為教授也是會員&#x20;

必須也要刪除員工資料表的同一筆關聯資料

![](/files/-LdhcotvttLjBKPQT6Yt)

結果有人選教授的課整個根本不能刪，必須找到原頭

### ##隱含交易模式 - 有錯 自動ROLLBACK&#xD;

但有一些學生是員工，但學生跟員工沒有關聯

用PK刪學生與員工資料，關聯不同基準點也不同

其實是兩筆交易會有不同可能性(成功 失敗 失敗 成功

此時就要將兩筆交易視為一筆交易

要使用

```
Begin  tran
第一筆交易
@@error 如果成功了此行的值就會是0
Begin
第二筆交易
@@error 如果成功
Commit
Else
rollback
End
Else
Rollback
```

![](/files/-LdhcxUGy4ccc4mkriL1)

不管幾次增刪修只會看到一次commit

因為只有所有確認都成功才會執行

但rollback就不止一次

第一筆交易如成功 會先塞在dbms 部分認可成功

然後等待第二筆

然後commit

### ##明顯交易處理&#xD;

![](/files/-Ldhd8SpaT2OOe_kprRj)

### ##併型控制&#xD;

![](/files/-Ldhd79cy11Nz4FszyCv)

買飲料

先到買很多

後到買很少

處理方式

先做買很少的

效率優先 ( 伺服器/個人電腦最佳化排程 ( 減少平均等待時間&#x20;

或

堅持原則先做先到的

先進先出 ( ATM

但伺服器多工呢 ( 可能不止 個位數的使用者

切成很多 time slot

輪流都做一點點 Q&#x20;

排隊理論

為了讓效率提升結果資料安全性降低 這是絕對不可以的

再來一些例子

![](/files/-LdhdMlQwyU54dfwPtjp)

![](/files/-LdhdRiPcMH6IFxtitEY)

![](/files/-LdhdaCuN2INGLwbLkZG)

![](/files/-Ldhde6CuLx-XU7Ypouq)

SQL SERVER 效能不如 歐洛摳 貴有貴的道理 ACCESS 更爛 更悲觀

樂觀就像乙太網路 CSMA/CD&#x20;

碰撞偵測 一次只能允許一個封包 碰撞時封包直接丟掉 換下一次舉手

以前10M現在10G 邏輯一樣但技術一直上升

網路塞車 ( 舉手的人太多 碰撞機率太高 就一直重複舉手 看誰最快舉手

Netcut原理

Arp –a

Osi七層&#x20;

Ip 第三

Mac第二detlinklayer 只認mac arp table紀錄傳送地址&#x20;

封掉這個

因為乙太網路是用廣播的三項交握跟這個傳遞方式不同

### ##網路要再加強 可以去查隔壁課程大綱自己看一下

![](/files/-LdheBEkKc2_3y3X_xpX)

![](/files/-LdheFIdsqT0kAUmySJI)

五個男生要追一個女生 大家都可以追

當女生決定跟一個男生再一起 其他四個無法追

但如果前面已經啟用共暫鎖定時要等待所有共暫鎖定處理完才能獨佔

![](/files/-LdheLocq0gb6OmofDze)

藉由意圖像是資料碰撞偵測邏輯的樣子?? 還是隨機給一個有意圖的使用者

### ##效能條教 - 補充 ( 上一個班沒講 我們賺到&#xD;

實務上的東西

Sql server 效能調教聖經 2000 - 2005

![](/files/-LdhewfpyV8i_i7NJFOl)

老師會的其實也是書上教的

資料讀取慢80%都是sql寫得不好

![](/files/-Ldhf2GHgrqBzUR92Lw6)

![](/files/-Ldhf7G_qjY-A5J81Tbb)

![](/files/-LdhfB2fBnbmWOD7X1SH)

不要欄位做運算會運算八百萬次

![](/files/-LdhfHK9USPVAFd7WyrQ)

也不要用

![](/files/-LdhfNzD-_40jIb2AHEl)

盡量避免用or

![](/files/-LdhfV6Cd7e6XxdRLbTW)

In>or

![](/files/-Ldhf_HJqVUlnegdIZUD)

不要用not

![](/files/-Ldhfdlsh_GnmWMFDbNZ)

子查詢效能差

![](/files/-LdhfksY60b1LVwC1lBk)

![](/files/-LdhfoEBCf_p0gU2raO6)

應該要再 dataset 在記憶體裡面操作 別用 資料庫資料操作

預存程序是編譯過的 可以省時間

![](/files/-LdhfuDSkh08MGkptzc9)

避免不必要的索引&#x20;

\#下午MVC

先從控制器C開始介紹後V再來M

M其實是最重要的能決定C跟V

上次是大架構

#### 題外話:ftp

![](/files/-Ldhg4k4PfwTIYJscB8A)

MVC專案裡面分為三個資料夾

會牽涉到namespace

只要沒有干涉到資料夾名稱就不用理會它

之前是m產c跟v

可是今天是只有c也是能執行，要看到介面只要有v就行

![](/files/-LdhgBGOdeTjro5AoFjn)

![](/files/-LdhgEzulFlX94JCn9i-)

![](/files/-LdhgIQaLUo9f2K-JR2m)

![](/files/-LdhgM399WIYxzVdfUf9)

專案名稱可以數字開頭

但namespace 不可以所以會出現底線

繼承Controller

來自於system.web.mvc

Actionresult為資料型態 有return且名稱index()

也沒有跟類別名稱一樣所以也不是建構子

所以是方法

回傳值 資料型態為 actionresult 物件型態

![](/files/-LdhgSgfr_Jb-_yiXsNY)

<http://xxxxx/controllerName/actionresult>

然後靠位址去要東西

這裡是<http://xxxxx/home/index>

就算沒有v也能跟他提要求

### ##homeController&#xD; **( 純控制器無v無m**

Actionresult物件型態 是專門 return view的

所以再建立一種方法showarry() 型態為 string 公開的

裡面塞個陣列，宣告string 最後來回傳結果

宣告個int來做計算

寫foreach函式作加總

隱含轉換

最後回傳string

預覽會錯誤因為是呼叫index()  function但裡面沒有對應的view檔案

所以用url呼叫另外一個我們剛寫的showarry() function

![](/files/-LdhgidMOHimjrqPykFs)

![](/files/-Ldhgkq6-t14nu96UpAJ)

#### 程式碼

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace _01Contorller.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        //02-1-3 建立一般方法ShowAry()-計算陣列總合
        public string ShowArray()
        {
            int[] score = { 78, 99, 20, 100, 66 };
            string show = "";
            int sum = 0;

            foreach(var m in score)
            {
                show += m + ", ";
                sum += m;
            }

            show += "，加總結果：" + sum;

            return show;

        }

    }
}

//02-1 Controller撰寫練習-一般方法
//02-1-1 在Controllers資料夾上按右鍵,加入,控制器,選擇 MVC5Controller-Empty
//02-1-2 指定控制器名稱為HomeController,並開啟HomeController
//02-1-3 建立一般方法ShowArray()-計算陣列總合
//02-1-4 執行並測試 http://localhost:53468/Home/ShowArray (port可能不同)
```

以上變數為區域變數所以下一個funtion可以繼續宣告同名稱變數

接著在一個funtion做練習 將圖片累加然後叫出來

```
public string ShowImages()
        {

            string show = "";
            for (int i=1;i<=8;i++)
            {
                show += "<img src='../images/"+i+".jpg' />";
            }
            return show;
        }

```

![](/files/-Ldhh3--CYGwV8G4aExD)

上面兩個都是一般方法 沒傳參數的

以下做個有傳參數的

Format 這個方法中 Index 會轉到 {0} 這

如何傳參數給方法??

<http://位址/位址?參數名稱=參數>

控制器無法做多載??

#### 最後程式碼與步驟&#xD;

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace _01Contorller.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        //02-1-3 建立一般方法ShowAry()-計算陣列總合
        public string ShowArray()
        {
            int[] score = { 78, 99, 20, 100, 66 };
            string show = "";
            int sum = 0;

            foreach(var m in score)
            {
                show += m + ", ";
                sum += m;
            }

            show += "，加總結果：" + sum;

            return show;

        }

        //02-1-5 建立一般方法ShowImages()-傳回顯示1.jpg~8.jpg的HTML字串
        public string ShowImages()
        {

            string show = "";
            for (int i=1;i<=8;i++)
            {
                show += "<img src='../images/"+i+".jpg' />";
            }
            return show;
        }

        //02-1-7 建立一般方法ShowImageIndex()-依index參數取得對應圖示與說明
        public string ShowImagesIndex(int index)
        {
            string[] name = { "櫻桃鴨", "鴨油高麗菜", "鴨油麻婆豆腐", "櫻桃鴨握壽司", "片皮鴨捲三星蔥", "三杯鴨", "櫻桃鴨片肉", "慢火白菜燉鴨湯" };
            string show = string.Format("<p align='center'><img src='../images/{0}.jpg' /><br />{1}</p>", index, name[index - 1]);

            return show;
        }

    }
}

//02-1 Controller撰寫練習-一般方法
//02-1-1 在Controllers資料夾上按右鍵,加入,控制器,選擇 MVC5Controller-Empty
//02-1-2 指定控制器名稱為HomeController,並開啟HomeController
//02-1-3 建立一般方法ShowArray()-計算陣列總合
//02-1-4 執行並測試 http://localhost:53468/Home/ShowArray (port可能不同)
//02-1-5 建立一般方法ShowImages()-傳回顯示images資料夾裡1.jpg~8.jpg的HTML字串
//02-1-6 執行並測試 http://localhost:53468/Home/ShowImages (port可能不同)
//02-1-7 建立一般方法ShowImageIndex()-依index參數取得對應圖示與說明
//02-1-8 執行並測試 http://localhost:53468/Home/ShowImageIndex?index=1 (port可能不同)

```

![](/files/-LdhhJhAFti_vGGQb1MY)

### ##簡單資料繫結 simplebind&#xD;

跟model有關繫

![](/files/-LdhhRuCwHMsrvUHpI0F)

{% embed url="<https://data-sci.info/2015/10/24/%E5%B8%B8%E8%A6%8B%E7%9A%84http-method%E7%9A%84%E4%B8%8D%E5%90%8C%E6%80%A7%E8%B3%AA%E5%88%86%E6%9E%90%EF%BC%9Agetpost%E5%92%8C%E5%85%B6%E4%BB%964%E7%A8%AEmethod%E7%9A%84%E5%B7%AE%E5%88%A5/>" %}

第一個新增是指get 做給view的

creat()

另一個是post 丟資料到資料庫去的

\[httppost] creat(參數)

![](/files/-Ldhhqr35LdS65MNwlS0)

沒有m產生v的精靈方式

沒有套版面配置所以較偏純html

{% embed url="<https://www.google.com/search?q=post+get&rlz=1C1GCEU_zh-TWTW835TW836&oq=post+get&aqs=chrome..69i57j69i65l3j0l2.4603j0j9&sourceid=chrome&ie=UTF-8>" %}

如果要把資料送出去

一定要有form (  Webform是要傳回server去編譯的

Method =”post” 這樣才會去找 httppost

Action=”/SimplaeBind/Create” 給去哪找action

但通常在view這邊要盡量不要寫死

利用Razor方式寫利用helper物件抓位址

```
<form method=”post” action=”@Url.Action(“Create”)”></form>
```

重點來了 輸入元件的name取的跟對應的action的參數名稱一樣就會自動綁定

Id雖然是給前端用的會取跟給後端用的name同樣的名稱避免麻煩

因為要傳資料要給type(但要看使用者瀏覽器支援不支援html5不然就要寫驗證

必填欄位所以加上 required

接著給一個傳遞按鍵

接著模擬送出後的回應

但要先去寫後端 control

利用 viewbag 保留狀態

通常送出後表單的值會被清空，要利用viewbag暫存顯示

接著把資料丟到 viewbag內

再回到前端view

利用razor寫helper將後端背包裡面的東西取出來

![](/files/-Ldhi8lLzJJtESQMfeV2)

### ##Razor 技巧 到底什麼時候要+@?&#xD;

指定@{ } 括弧內不用加 但是如果 \<htmltag>@{}\</htmltag>&#x20;

被html包覆就要重新宣告 razor 區域

Webform會幫你預設保留狀態 就是純html裡面的封裝過的亂碼 viewstate&#x20;

{% embed url="<https://www.google.com/search?q=webform+viewstate&rlz=1C1GCEU_zh-TWTW835TW836&oq=webform+viewstate&aqs=chrome..69i57j0l4.8187j0j4&sourceid=chrome&ie=UTF-8>" %}

![](/files/-LdhiOd_r7erB8LkqOIZ)

http正常是走 request response 資料傳過去後端時前端資料就會消失

{% embed url="<https://www.google.com/search?q=request+response&rlz=1C1GCEU_zh-TWTW835TW836&oq=request+r&aqs=chrome.3.69i57j0l5.12168j0j9&sourceid=chrome&ie=UTF-8>" %}

mvc 就是正常http狀態 不會預設保留

保留必須要寫 例如說 把viewbag裡面的東西回傳給 text

![](/files/-LdhiYibm5leGIMBfPrH)

MVC網頁狀態處理元件 viewbag station??

#### 程式碼&#xD;

#### 前端&#xD;create view

```
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>產品新增</title>
</head>
<body>

    @*<form method="post" action="/SimpleBind/Create">*@
    <form method="post" action="@Url.Action("Create")">
        <h2>產品增作業</h2>
        <div>
            <p>編號：<input id="PId" name="PId" type="text" value="@ViewBag.PId" required /></p>
            <p>品名：<input id="PName" name="PName" type="text" value="@ViewBag.PName" required /></p>
            <p>單價：<input id="Price" name="Price" type="number" value="@ViewBag.Price" required /></p>
            <p><input id="Submit1" type="submit" value="新增商品" /></p>
            <hr />
            @{ 
                if(ViewBag.PId!=null && ViewBag.PName!=null && ViewBag.Price!=null)
                {
                    <h2>產品增作業完成!!!!</h2>
                    <h3>編號：@ViewBag.PId, 品名：@ViewBag.PName, 單價：@ViewBag.Price</h3>
                }
            }
        </div>


    </form>

   
</body>
</html>



```

#### 後端 simplebindcontroller

```

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace _01Contorller.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        //02-1-3 建立一般方法ShowAry()-計算陣列總合
        public string ShowArray()
        {
            int[] score = { 78, 99, 20, 100, 66 };
            string show = "";
            int sum = 0;

            foreach(var m in score)
            {
                show += m + ", ";
                sum += m;
            }

            show += "，加總結果：" + sum;

            return show;

        }

        //02-1-5 建立一般方法ShowImages()-傳回顯示1.jpg~8.jpg的HTML字串
        public string ShowImages()
        {

            string show = "";
            for (int i=1;i<=8;i++)
            {
                show += "<img src='../images/"+i+".jpg' />";
            }
            return show;
        }

        //02-1-7 建立一般方法ShowImageIndex()-依index參數取得對應圖示與說明
        public string ShowImagesIndex(int index)
        {
            string[] name = { "櫻桃鴨", "鴨油高麗菜", "鴨油麻婆豆腐", "櫻桃鴨握壽司", "片皮鴨捲三星蔥", "三杯鴨", "櫻桃鴨片肉", "慢火白菜燉鴨湯" };
            string show = string.Format("<p align='center'><img src='../images/{0}.jpg' /><br />{1}</p>", index, name[index - 1]);

            return show;
        }

    }
}



//02-2 簡單模型繫結
//02-2-1 在Controllers資料夾上按右鍵,加入,控制器,選擇 MVC5Controller-Empty
//02-2-2 指定控制器名稱為SimpleBindController,並開啟SimpleBindController
//02-2-3 建立GET與POST的Create方法
//02-2-4 在public ActionResult Create()上按右鍵,新增檢視,建立Create View
//02-2-5 進行下列設定:
//       View name:Create
//       Template:Empty(without model)
//       不勾選Use a layout pages
//       按下Add
//02-2-6 修改title文字與加入form內容
//02-2-7 執行並測試 http://localhost:53468/SimpleBind/Create (port可能不同)

```

### ##複雜繫結complexbind&#xD;

簡單繫結是 前端NAME 與 後端參數NAME&#x20;

但當參數很多的時候不就一堆

複雜繫結是配合M複雜繫結會相對於簡單繫結方便

首先在M新增class 其實 model ADO.net也是 class

![](/files/-LdhjouF_1GTZVkm32gT)

![](/files/-LdhjumsU62__74xgURe)

再來再新增一個控制器

簡單繫結跟複雜主要是差在傳參數方式

藉由剛剛新增的類別直接傳入

![](/files/-Ldhk0cuvOhB8kdu-_Z_)

然後view不用動 但是 name 必須前端name跟後端控制器name一樣

#### 建構子是建構子，funtion是funtion，class是class&#xD;

{% embed url="<https://www.google.com/search?q=new+%E5%BB%BA%E6%A7%8B%E5%AD%90+%E6%99%82%E6%A9%9F&oq=new+%E5%BB%BA%E6%A7%8B%E5%AD%90+%E6%99%82%E6%A9%9F&aqs=chrome..69i57.15293j0j4&client=ms-android-xiaomi&sourceid=chrome-mobile&ie=UTF-8>" %}

#### 程式碼&#xD;

#### 前端 create view&#x20;

```
@{
    Layout = null;
}
@*//02-2-6 修改title文字與加入form內容*@
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>產品新增</title>
</head>
<body>

    @*<form method="post" action="/SimpleBind/Create">*@
    <form method="post" action="@Url.Action("Create")">
        <h2>產品增作業</h2>
        <div>
            <p>編號：<input id="PId" name="PId" type="text" value="@ViewBag.PId" required /></p>
            <p>品名：<input id="PName" name="PName" type="text" value="@ViewBag.PName" required /></p>
            <p>單價：<input id="Price" name="Price" type="number" value="@ViewBag.Price" required /></p>
            <p><input id="Submit1" type="submit" value="新增商品" /></p>
            <hr />
            @{
                if (ViewBag.PId != null && ViewBag.PName != null && ViewBag.Price != null)
                {
                    <h2>產品增作業完成!!!!</h2>
                    <h3>編號：@ViewBag.PId, 品名：@ViewBag.PName, 單價：@ViewBag.Price</h3>
                }
            }
        </div>


    </form>


</body>
</html>

```

#### &#x20;後端complexbindcontroller

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using _01Contorller.Models;

namespace _01Contorller.Controllers
{
    public class ComplexBindController : Controller
    {
        // GET: ComplexBind
        //public ActionResult Index()
        //{
        //    return View();
        //}

        //02-3-6 建立GET與POST的Create方法
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Product p)
        {
            ViewBag.PId = p.PId;
            ViewBag.PName = p.PName;
            ViewBag.Price = p.Price;

            return View();
        }


    }
}

類別模組
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace _01Contorller.Models
{
    public class Product
    {
        public string PId { get; set; }
        public string PName { get; set; }
        public string Price { get; set; }
    }
}

```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://johch3n611u.gitbook.io/c50108/ju-li-cheng-bei/201904/untitled-12.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
