EF框架基礎

農碼一生發表於2022-04-02

ORM概述:

ORM全稱是“物件 - 關係對映” 。

ORM是將關聯式資料庫中的資料用物件的形式表現出來,並通過物件導向的方式將這些物件組織起來,實現系統業務邏輯的過程。

Entity Framework(簡稱EF):

ASP.NET MVC應用程式推薦使用的ORM框架;

支援多種資料庫;

對映引擎支援儲存過程;

提供Visual Studio整合工具,執行視覺化操作;

一、資料準備

本教程使用具體例項進行演示EF的基本使用,需要用資料庫以及一些工具類。

資料表結構指令碼:

create table Dept --部門資訊
(
	DeptId int primary key identity(1,1),
	DeptName varchar(50) not null
)

create table Employee	--員工資訊
(
	EmpId int primary key identity(1,1),
	DeptId int not null,
	EmpName varchar(50) not null,
	EmpPhone varchar(50) not null,
	EmpArea varchar(50) not null,
	EmpSalary decimal(18,2) not null
)

insert into Dept(DeptName) values('開發部')
insert into Dept(DeptName) values('測試部')
insert into Dept(DeptName) values('實施部')

insert into Employee(DeptId,EmpName,EmpPhone,EmpArea,EmpSalary)
values(1,'劉德華','13887855552','武漢',6500)
insert into Employee(DeptId,EmpName,EmpPhone,EmpArea,EmpSalary)
values(2,'張學友','13556528634','深圳',6500)
insert into Employee(DeptId,EmpName,EmpPhone,EmpArea,EmpSalary)
values(3,'劉亦菲','13448494546','廣州',6500)
insert into Employee(DeptId,EmpName,EmpPhone,EmpArea,EmpSalary)
values(1,'周杰倫','13888666855','北京',6500)
insert into Employee(DeptId,EmpName,EmpPhone,EmpArea,EmpSalary)
values(2,'許巍','13868654219','上海',6500)
insert into Employee(DeptId,EmpName,EmpPhone,EmpArea,EmpSalary)
values(3,'孫燕姿','13895133572','成都',6500)
insert into Employee(DeptId,EmpName,EmpPhone,EmpArea,EmpSalary)
values(1,'朴樹','13458788896','武漢',6500)
insert into Employee(DeptId,EmpName,EmpPhone,EmpArea,EmpSalary)
values(2,'周潤發','13554588745','南京',6500)
insert into Employee(DeptId,EmpName,EmpPhone,EmpArea,EmpSalary)
values(3,'李連杰','13998759654','上海',6500)

select * from Dept;
select * from Employee;

匿名類集合轉動態屬性:

public class MyDynamic
{
    public static List<ExpandoObject> ToExpandoList(object query)
    {
        List<ExpandoObject> listExpando = new List<ExpandoObject>();
        foreach (var entity in (IEnumerable)query)
        {
            Type type = entity.GetType();
            dynamic dyEntity = new ExpandoObject();
            IDictionary<string, object> dict = new Dictionary<string, object>();
            dict = dyEntity as ExpandoObject;
            PropertyInfo[] arrProperty = type.GetProperties();
            foreach (PropertyInfo prop in arrProperty)
            {
                string a = prop.Name;
                string b = prop.GetValue(entity, null).ToString();
                dict.Add(prop.Name, prop.GetValue(entity, null));
            }
            listExpando.Add(dict as dynamic);
        }
        return listExpando;
    }
}

二、EF實現增刪改查

在控制器中建立資料庫操作類物件:

DBTESTEntities db = new DBTESTEntities();

(1)實現資料列表

Action:

public ActionResult Index()
{     
        	   
    var listView = from emp in db.Employee
                    join dept in db.Dept on emp.DeptId equals dept.DeptId
                    select new
                    {
                        EmpId = emp.EmpId,
                        DeptId = emp.DeptId,
                        DeptName = dept.DeptName,
                        EmpName = emp.EmpName,
                        EmpPhone = emp.EmpPhone,
                        EmpArea = emp.EmpArea,
                        EmpSalary = emp.EmpSalary
                    };
    ViewBag.listView = MyDynamic.ToExpandoList(listView);
    return View();
}

View:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <style type="text/css">
        div, table, tr, td {
            margin: 0px;
            padding: 0px;
        }

        .myTable {
            width: 800px;
            margin: 20px;
            border-collapse: collapse;
        }

            .myTable td,.myTable th {
                height: 30px;
                line-height: 30px;
                padding: 6px;
            }
    </style>
</head>
<body>
    <div> 
        <h1>查詢員工資訊</h1>
        <a href="AddForm">新增員工</a> <br /><br />
        <table width="1000" border="1" class="myTable">
            <tr>
                <th>員工編號</th>
                <th>部門名稱</th>
                <th>員工姓名</th>
                <th>員工電話</th>
                <th>所在地區</th>
                <th>員工工資</th>
                <th>操作</th>
            </tr>
            @foreach (var item in ViewBag.listView)
            {
                <tr>
                    <td>@item.EmpId</td>
                    <td>@item.DeptName</td>
                    <td>@item.EmpName</td>
                    <td>@item.EmpPhone</td>
                    <td>@item.EmpArea</td>
                    <td>@item.EmpSalary.ToString("F2")</td>
                    <td>
                        <a href="UpdateForm?EmpId=@item.EmpId">編輯</a> |
                        <a href="Delete?EmpId=@item.EmpId" onclick="return confirm('確定刪除嗎');">刪除</a>
                    </td>
                </tr>
            }
        </table>
    </div>
</body>
</html>

(2)實現資料新增

新增頁面Action:

public ActionResult AddForm()
{
    //查詢所有部門
    ViewBag.listDept = db.Dept.ToList();
    return View();
}

新增頁面檢視:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>AddForm</title>
    <style type="text/css">
        div, table, tr, td {
            margin: 0px;
            padding: 0px;
        }
        .myTable {
            width: 800px;
            margin: 20px auto;
            border-collapse: collapse;
        }
        .myTable td {
            height: 30px;
            line-height: 30px;
            padding: 6px;
        }
    </style>
</head>
<body>
    <form method="post" action="~/Home/Add">
        <div style="text-align:center;">
            <table width="800" class="myTable" border="1">
                <tr>
                    <td colspan="2" align="center" style="font-weight:bold;">員工新增</td>
                </tr>
                <tr>
                    <td width="200" align="right">所屬部門:</td>
                    <td width="600" align="left">
                        <select name="DeptId" id="DeptId">
                            <option value="0">--請選擇--</option>
                            @foreach (var item in ViewBag.listDept)
                            {
                                <option value="@item.DeptId">@item.DeptName</option>
                            }
                        </select>
                    </td>
                </tr>
                <tr>
                    <td width="200" align="right">員工姓名:</td>
                    <td width="600" align="left"><input type="text" name="txtRealName" /></td>
                </tr>
                <tr>
                    <td width="200" align="right">員工電話:</td>
                    <td width="600" align="left"><input type="text" name="txtPhone" /></td>
                </tr>
                <tr>
                    <td width="200" align="right">所在城市:</td>
                    <td width="600" align="left"><input type="text" name="txtArea" /></td>
                </tr>
                <tr>
                    <td width="200" align="right">月薪:</td>
                    <td width="600" align="left"><input type="text" name="txtSalary" /></td>
                </tr>
                <tr>
                    <td width="200" align="right"></td>
                    <td width="600" align="left">
                        <input type="submit" value="新增" />
                        <a href="Index">返回首頁</a>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

處理新增提交請求的Action:

public ActionResult Add()
{
    //執行新增操作
    //Employee emp = new Employee();
    //emp.DeptId = int.Parse(Request["DeptId"]);
    //emp.EmpName = Request["txtRealName"];
    //emp.EmpPhone = Request["txtPhone"];
    //emp.EmpArea = Request["txtArea"];
    //emp.EmpSalary = decimal.Parse(Request["txtSalary"]);
    //db.Employee.Add(emp);
    //db.SaveChanges();

    //EF框架執行sql語句
    string sql = "insert into Employee(DeptId,EmpName,EmpPhone,EmpArea,EmpSalary) values(@DeptId,@EmpName,@EmpPhone,@EmpArea,@EmpSalary)";
    SqlParameter DeptId = new SqlParameter("@DeptId", int.Parse(Request["DeptId"]));
    SqlParameter EmpName = new SqlParameter("@EmpName", Request["txtRealName"]);
    SqlParameter EmpPhone = new SqlParameter("@EmpPhone", Request["txtPhone"]);
    SqlParameter EmpArea = new SqlParameter("@EmpArea", Request["txtArea"]);
    SqlParameter EmpSalary = new SqlParameter("@EmpSalary", decimal.Parse(Request["txtSalary"]));
    int rowCount = db.Database.ExecuteSqlCommand(sql,DeptId, EmpName, EmpPhone, EmpArea, EmpSalary);
    return Content("<script >alert('新增成功!');window.location.href='AddForm';</script >", "text/html");
}

(3)實現資料編輯修改

編輯頁面Action:

public ActionResult UpdateForm()
{
    //查詢所有部門
    ViewBag.listDept = db.Dept.ToList();
    //查詢員工詳情
    ViewBag.emp = db.Employee.Find(int.Parse(Request["EmpId"]));          
    return View();
}

編輯頁面檢視:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>UpdateForm</title>
    <style type="text/css">
        div, table, tr, td {
            margin: 0px;
            padding: 0px;
        }

        .myTable {
            width: 800px;
            margin: 20px auto;
            border-collapse: collapse;
        }

            .myTable td {
                height: 30px;
                line-height: 30px;
                padding: 6px;
            }
    </style>
</head>
<body>
    <form method="post" action="~/Home/Update">
        <div style="text-align:center;">
            <input type="hidden" name="hdEmpId" value="@ViewBag.emp.EmpId" />
            <table width="800" class="myTable" border="1">
                <tr>
                    <td colspan="2" align="center" style="font-weight:bold;">員工修改</td>
                </tr>
                <tr>
                    <td width="200" align="right">所屬部門:</td>
                    <td width="600" align="left">
                        <select name="DeptId" id="DeptId">
                            <option value="0">--請選擇--</option>
                            @foreach (var item in ViewBag.listDept)
                            {
                                
                                <option value="@item.DeptId" @(item.DeptId == ViewBag.emp.DeptId ? "selected" : "")>@item.DeptName</option>
                            }
                        </select>
                    </td>
                </tr>
                <tr>
                    <td width="200" align="right">員工姓名:</td>
                    <td width="600" align="left"><input type="text" name="txtRealName" value="@ViewBag.emp.EmpName" /></td>
                </tr>
                <tr>
                    <td width="200" align="right">員工電話:</td>
                    <td width="600" align="left"><input type="text" name="txtPhone" value="@ViewBag.emp.EmpPhone" /></td>
                </tr>
                <tr>
                    <td width="200" align="right">所在城市:</td>
                    <td width="600" align="left"><input type="text" name="txtArea" value="@ViewBag.emp.EmpArea" /></td>
                </tr>
                <tr>
                    <td width="200" align="right">月薪:</td>
                    <td width="600" align="left"><input type="text" name="txtSalary" value="@ViewBag.emp.EmpSalary" /></td>
                </tr>
                <tr>
                    <td width="200" align="right"></td>
                    <td width="600" align="left">
                        <input type="submit" value="修改" />
                        <a href="Index">返回首頁</a>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

處理修改請求的Action:

public ActionResult Update()
{
    //EF框架執行修改操作
    //int empId = int.Parse(Request["hdEmpId"]);
    //Employee emp = db.Employee.Find(empId);
    //emp.DeptId = int.Parse(Request["DeptId"]);
    //emp.EmpName = Request["txtRealName"];
    //emp.EmpPhone = Request["txtPhone"];
    //emp.EmpArea = Request["txtArea"];
    //emp.EmpSalary = decimal.Parse(Request["txtSalary"]);
    //db.SaveChanges();

    //EF框架執行sql語句
    int empId = int.Parse(Request["hdEmpId"]);
    string sql = "update Employee set DeptId=@DeptId,EmpName=@EmpName,EmpPhone=@EmpPhone,EmpArea=@EmpArea,EmpSalary=@EmpSalary where EmpId=@EmpId";
    SqlParameter DeptId = new SqlParameter("@DeptId", int.Parse(Request["DeptId"]));
    SqlParameter EmpName = new SqlParameter("@EmpName", Request["txtRealName"]);
    SqlParameter EmpPhone = new SqlParameter("@EmpPhone", Request["txtPhone"]);
    SqlParameter EmpArea = new SqlParameter("@EmpArea", Request["txtArea"]);
    SqlParameter EmpSalary = new SqlParameter("@EmpSalary", decimal.Parse(Request["txtSalary"]));
    SqlParameter EmpId = new SqlParameter("@EmpId", empId);
    int rowCount = db.Database.ExecuteSqlCommand(sql,DeptId, EmpName, EmpPhone, EmpArea, EmpSalary, EmpId);
    return Content("<script >alert('修改成功!');window.location.href='UpdateForm?EmpId="+ empId + "';</script >", "text/html");
}

(4)實現資料的刪除

處理刪除請求的Action:

public ActionResult Delete()
{
    //EF框架執行刪除操作
    //int empId = int.Parse(Request["EmpId"]);
    //Employee emp = db.Employee.Find(empId);
    //db.Employee.Remove(emp);
    //db.SaveChanges();

    //EF框架執行SQL語句
    int empId = int.Parse(Request["EmpId"]);
    string sql = "delete from Employee where EmpId = @EmpId";
    SqlParameter EmpId = new SqlParameter("@EmpId", empId);
    int rowCount = db.Database.ExecuteSqlCommand(sql,EmpId);
    return Content("<script >alert('刪除成功!');window.location.href='Index';</script >", "text/html");
}

三、組合條件搜尋+分頁

搜尋頁面Action:

public ActionResult SearchForm()
{
    var listView = from emp in db.Employee
                    join dept in db.Dept on emp.DeptId equals dept.DeptId
                    select new
                    {
                        EmpId = emp.EmpId,
                        DeptId = emp.DeptId,
                        DeptName = dept.DeptName,
                        EmpName = emp.EmpName,
                        EmpPhone = emp.EmpPhone,
                        EmpArea = emp.EmpArea,
                        EmpSalary = emp.EmpSalary
                    };
    //新增查詢條件
    if (!string.IsNullOrEmpty(Request["ddlDept"]))
    {
        //linq to entity,不能在lambda裡面進行int.parse,或者其它的顯示隱式的轉換,所以將型別轉換寫在外面 或者下述方案也可以解決
        //此處如果進行型別轉換例如ToString(),int.Parse()會報錯,可以上面的listView轉換為LinqToObject,即db.Employee和db.Dept都呼叫AsEnumerable。
        int deptId = int.Parse(Request["ddlDept"]);
        listView = listView.Where(p => p.DeptId == deptId);
    }
    if (!string.IsNullOrEmpty(Request["txtRealName"]))
    {
        //linq to entity,不能在lambda裡面進行int.parse,或者其它的顯示隱式的轉換
        string realName = Request["txtRealName"].ToString();
        listView = listView.Where(p => p.EmpName.Contains(realName));
    }

    //處理分頁
    int pageSize = 5;  //頁碼大小
    int pageIndex = 1; //當前頁碼
    if (!string.IsNullOrEmpty(Request["page"]))
        pageIndex = int.Parse(Request["page"]);
    int recordCount = listView.Count();  //總記錄條數量
    //總共頁數
    int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : recordCount / pageSize + 1;
    if (pageIndex > pageCount) pageIndex = pageCount;
    if (pageIndex < 1) pageIndex = 1;
    listView = listView.OrderBy(p => p.EmpId).Skip(pageSize * (pageIndex - 1)).Take(pageSize);

    ViewBag.listView = MyDynamic.ToExpandoList(listView);
    //查詢所有部門
    ViewBag.listDept = db.Dept.ToList();
    //記錄頁碼大小,當前頁和總頁數
    ViewBag.pageSize = pageSize;
    ViewBag.pageIndex = pageIndex;
    ViewBag.pageCount = pageCount;
    return View();
}

搜尋頁面檢視:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>多條件組合搜尋+分頁</title>
</head>
<body>
    <h1>查詢員工資訊</h1>
    <form action="SearchForm" method="post">
        <div style="height:30px; line-height:30px;">
            所屬部門:
            <select name="ddlDept" id="ddlDept">
                <option value="">--請選擇--</option>
                @foreach (var item in ViewBag.listDept)
                {
                    int deptId = 0;
                    if (!string.IsNullOrEmpty(Request["ddlDept"]))
                    {
                        deptId = int.Parse(Request["ddlDept"]);
                    }
                    <option value="@item.DeptId" @(item.DeptId == deptId ? "selected" : "")>@item.DeptName</option>
                }
            </select>
            員工姓名:
            <input type="text" name="txtRealName" id="txtRealName" value="@Request["txtRealName"]" />
            <input type="submit" value="搜尋" />
        </div>
    </form>
    <div> 
        <table width="1000" border="1" class="myTable">
            <tr>
                <th>員工編號</th>
                <th>部門名稱</th>
                <th>員工姓名</th>
                <th>員工電話</th>
                <th>所在地區</th>
                <th>員工工資</th>
            </tr>
            @foreach (var item in ViewBag.listView)
            {
                <tr>
                    <td>@item.EmpId</td>
                    <td>@item.DeptName</td>
                    <td>@item.EmpName</td>
                    <td>@item.EmpPhone</td>
                    <td>@item.EmpArea</td>
                    <td>@item.EmpSalary.ToString("F2")</td>
                </tr>
            }
        </table>
    </div>
    @{string urlParama = "ddlDept=" + Request["ddlDept"] + "&txtRealName=" + Request["txtRealName"];}
    <form action="SearchForm?@urlParama" method="post">
        <div style="height:30px; line-height:30px;">
            <a href="SearchForm?page=1&@urlParama">首頁</a>
            <a href="SearchForm?page=@(ViewBag.pageIndex-1)&@urlParama">上一頁</a>
            <a href="SearchForm?page=@(ViewBag.pageIndex+1)&@urlParama">下一頁</a>
            <a href="SearchForm?page=@ViewBag.pageCount&@urlParama">末頁</a>
            轉到:<input name="page" type="text" style="width:30px;" value="@ViewBag.pageIndex" />頁 
            <input type="submit" value="GO" />
            當前第<span style="color:orangered;">@ViewBag.pageIndex</span>頁
            共<span style="color:orangered;">@ViewBag.pageCount</span>頁
        </div>
    </form>
</body>
</html>

四、JPager外掛實現分頁

本案例同樣實現組合條件+分頁的功能,只是分頁功能使用Jpager來實現,JPager外掛可以在Nuget中進行安裝。

安裝完成後引入名稱空間:

using JPager.Net;

Action:

public ActionResult Index(PagerInBase param)
{
    param.PageSize = 3;
    var list = from emp in db.Employee
                    join dept in db.Dept on emp.DeptId equals dept.DeptId
                    select new EmpAndDept
                    {
                        EmpId = emp.EmpId,
                        DeptId = emp.DeptId,
                        DeptName = dept.DeptName,
                        EmpName = emp.EmpName,
                        EmpPhone = emp.EmpPhone,
                        EmpArea = emp.EmpArea,
                        EmpSalary = emp.EmpSalary
                    };
    if (!string.IsNullOrEmpty(Request["DeptId"]))
    {
        int deptId = int.Parse(Request["DeptId"]);
        list = list.Where(p => p.DeptId == deptId);
    }
    if (!string.IsNullOrEmpty(Request["EmpName"]))
    {
        string EmpName = Request["EmpName"].ToString();
        list = list.Where(p => p.EmpName.Contains(EmpName));
    }

    var data = list.OrderBy(p=>p.EmpId).Skip(param.Skip).Take(param.PageSize);
    var count = list.Count();
    var res = new PagerResult<EmpAndDept>
    {
        Code = 0,
        DataList = data,
        Total = count,
        PageSize = param.PageSize,
        PageIndex = param.PageIndex,
        RequestUrl = param.RequetUrl
    };
    ViewBag.ListDept = db.Dept;
    ViewBag.res = res;
    return View();
}

View:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <style type="text/css">

    </style>
</head>
<body>
    <h1>查詢員工資訊</h1>
    <a href="AddForm">新增員工</a> <br /><br />
    <form method="get" action="Index">
        <p>
            部門:
            <select name="DeptId">
                <option value="">--請選擇--</option>
                @foreach (var item in ViewBag.ListDept)
                {
                    int deptId = 0;
                    if (!string.IsNullOrEmpty(Request["DeptId"]))
                    {
                        deptId = int.Parse(Request["DeptId"]);
                    }
                    <option value="@item.DeptId" @(item.DeptId == deptId ? "selected" : "")>@item.DeptName</option>
                }
            </select>
            姓名:
            <input type="text" name="EmpName" value="@Request["EmpName"]" />
            <input type="submit" value="搜 索" />
        </p>
    </form>

    <table width="1000" border="1" class="myTable">
        <tr>
            <th>員工編號</th>
            <th>部門名稱</th>
            <th>員工姓名</th>
            <th>員工電話</th>
            <th>所在地區</th>
            <th>員工工資</th>
            <th>操作</th>
        </tr>
        @foreach (var item in ViewBag.res.DataList)
        {
            <tr>
                <td>@item.EmpId</td>
                <td>@item.DeptName</td>
                <td>@item.EmpName</td>
                <td>@item.EmpPhone</td>
                <td>@item.EmpArea</td>
                <td>@item.EmpSalary.ToString("F2")</td>
                <td>
                    <a href="UpdateForm?EmpId=@item.EmpId">編輯</a> |
                    <a href="Delete?EmpId=@item.EmpId" onclick="return confirm('確定刪除嗎');">刪除</a>
                </td>
            </tr>
        }
    </table>
    <div id="mypage">
        @Html.Raw(ViewBag.res.PagerHtml()) 共 @ViewBag.res.Total 條
    </div>
</body>
</html>

五、PagedList外掛實現分頁

本案例同樣實現組合條件+分頁的功能,只是分頁功能使用PagedList.MVC來實現,PagedList.MVC外掛可以在Nuget中進行安裝。

安裝完成後引入名稱空間:

using PagedList;

Action:

public ActionResult Index(int page = 1)
{
    var query = from emp in db.Employee
                join dept in db.Dept on emp.DeptId equals dept.DeptId
                select new EmpAndDept
                {
                    EmpId = emp.EmpId,
                    DeptId = emp.DeptId,
                    EmpName = emp.EmpName,
                    EmpPhone = emp.EmpPhone,
                    EmpArea = emp.EmpArea,
                    EmpSalary = emp.EmpSalary,
                    DeptName = dept.DeptName
                };
    //新增查詢條件
    if (!string.IsNullOrEmpty(Request["DeptId"]))
    {
        //linq to entity,不能在lambda裡面進行int.parse,或者其它的顯示隱式的轉換,所以將型別轉換寫在外面 或者下述方案也可以解決
        //此處如果進行型別轉換例如ToString(),int.Parse()會報錯,可以上面的listView轉換為LinqToObject,即db.Employee和db.Dept都呼叫AsEnumerable。
        int deptId = int.Parse(Request["DeptId"]);
        query = query.Where(p => p.DeptId == deptId);
    }
    if (!string.IsNullOrEmpty(Request["EmpName"]))
    {
        //linq to entity,不能在lambda裡面進行int.parse,或者其它的顯示隱式的轉換
        string realName = Request["EmpName"].ToString();
        query = query.Where(p => p.EmpName.Contains(realName));
    }
    int pagesize = 2;
    var data = query.OrderByDescending(p => p.EmpId).ToPagedList(page, pagesize);
    ViewBag.ListDept = db.Dept;
    ViewBag.DataList = data;
    return View();
}

View:

@using PagedList;
@using PagedList.Mvc;
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h1>查詢員工資訊</h1>
    <a href="AddForm">新增員工</a> <br /><br />
    <form method="get">
        <p>
            部門:
            <select name="DeptId">
                <option value="">--請選擇--</option>
                @foreach (var item in ViewBag.ListDept)
                {
                    int deptId = 0;
                    if (!string.IsNullOrEmpty(Request["DeptId"]))
                    {
                        deptId = int.Parse(Request["DeptId"]);
                    }
                    <option value="@item.DeptId" @(item.DeptId == deptId ? "selected" : "")>@item.DeptName</option>
                }
            </select>
            姓名:
            <input type="text" name="EmpName" value="@Request["EmpName"]" />
            <input type="submit" value="搜 索" />
        </p>
    </form>

    <table width="1000" border="1" class="myTable">
        <tr>
            <th>員工編號</th>
            <th>部門名稱</th>
            <th>員工姓名</th>
            <th>員工電話</th>
            <th>所在地區</th>
            <th>員工工資</th>
            <th>操作</th>
        </tr>
        @foreach (var item in ViewBag.DataList)
        {
            <tr>
                <td>@item.EmpId</td>
                <td>@item.DeptName</td>
                <td>@item.EmpName</td>
                <td>@item.EmpPhone</td>
                <td>@item.EmpArea</td>
                <td>@item.EmpSalary.ToString("F2")</td>
                <td>
                    <a href="UpdateForm?EmpId=@item.EmpId">編輯</a> |
                    <a href="Delete?EmpId=@item.EmpId" onclick="return confirm('確定刪除嗎');">刪除</a>
                </td>
            </tr>
        }
    </table>
    <div>      
        @Html.PagedListPager((IPagedList)ViewBag.DataList, page => Url.Action("Index", new { page, DeptId=Request["DeptId"], EmpName=Request["EmpName"] }))
    </div>
</body>
</html>

六、EF中執行SQL查詢

在EF中執行非查詢操作,在前面的例子程式碼中已經出現過,此處不做描述,此處主要描述在EF中做SQL查詢操作。

Action:

public ActionResult SqlQueryForm()
{
    DBTESTEntities db = new DBTESTEntities();
    var count = db.Database.SqlQuery<int>("select count(*) from Employee");
    ViewBag.count = count.FirstOrDefault();

    var query1 = db.Database.SqlQuery<Employee>("select * from Employee");
    ViewBag.listView1 = query1;
    
    //如果查詢的結果找不到對應的實體,需要單獨定義一個類,返回的資料必須數量和名字都與此類屬性相同

    //如果查詢出的資料需要修改,有如下2種方案
    //方案一:
    //Employee emp = db.Employee.SqlQuery("select * from Employee where EmpId = 1").FirstOrDefault();
    //emp.EmpSalary += 100;
    //db.SaveChanges();

    //方案二:
    //Employee emp = db.Database.SqlQuery<Employee>("select * from Employee where EmpId = 1").FirstOrDefault();
    //emp.EmpSalary += 100;
    //db.Entry<Employee>(emp).State = System.Data.Entity.EntityState.Modified;
    //db.SaveChanges();

    return View();
}

View:

<div>
    <h2>使用EF中SQL語句進行查詢員工資料,員工數量:@ViewBag.count</h2>
    <table width="1000" border="1" class="myTable">
        <tr>
            <th>員工編號</th>
            <th>部門編號</th>
            <th>員工姓名</th>
            <th>員工電話</th>
            <th>所在地區</th>
            <th>員工工資</th>
        </tr>
        @foreach (var item in ViewBag.listView1)
        {
            <tr>
                <td>@item.EmpId</td>
                <td>@item.DeptId</td>
                <td>@item.EmpName</td>
                <td>@item.EmpPhone</td>
                <td>@item.EmpArea</td>
                <td>@item.EmpSalary.ToString("F2")</td>
            </tr>
        }
    </table>
</div>

相關文章