iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 27
2
Software Development

從問題理解與活用SQL語法系列 第 27

第二十七堂:英文單字測驗程式 - 學生帳號資料管理(6) - 物件實體操作資料 (ORM、Entity Framework)

  • 分享至 

  • twitterImage
  •  

一、課程程式專案與資料庫範本SQL Github

https://github.com/ted59438/EnglishVocabulary_MySQL

  • EnglishVocabularyLearning.exe:英文單字測驗最終的實作結果
  • DBPlayground:課堂的C#範例專案
  • EnglishVocabularyLearning_MySQL:C#練習專案
  • EnglishVocabulary.sql:MySQL的範本資料
  • EnglishVocabulary_MSSQL.sql:SQL Server 的範本資料

二、前置作業

(一) 安裝 MySQL For Visual Studio 1.2.8

https://dev.mysql.com/downloads/windows/visualstudio/

(二) 安裝 MySQL Connector/NET 6.9.12

https://downloads.mysql.com/archives/c-net/

(三) 將 MySQL Connector/NET 6.9.12 的Library DLL 加入專案

C# 連接 MySQL 需要 MySQL 提供的DLL Library

https://ithelp.ithome.com.tw/upload/images/20191013/201203316oNPsnM1q2.png

https://ithelp.ithome.com.tw/upload/images/20191013/20120331hMddSqynAf.png

(四) 加入ADO.NET 實體資料模型 (所有資料表的實體物件)

產生完後,就可以透過產生出來的物件類別,以ORM的方式來進行資料操作
https://ithelp.ithome.com.tw/upload/images/20191013/20120331S1HSD7N1tC.png

https://ithelp.ithome.com.tw/upload/images/20191013/201203314fgZOscP98.png

https://ithelp.ithome.com.tw/upload/images/20191013/20120331mabvhvMymH.png

https://ithelp.ithome.com.tw/upload/images/20191013/20120331L0blF3ODJH.png

https://ithelp.ithome.com.tw/upload/images/20191013/20120331Odt58dyXeA.png

https://ithelp.ithome.com.tw/upload/images/20191013/20120331eRhrQTjF0K.png

三、課堂內容

(一) 認識ORM

Object Relational Mapping, ORM,一種將關聯式資料庫轉換對應成為物件的抽象化技術,好處是可以讓開發者直接使用物件導向方式對資料庫進行操作

Entity Framework 是 C# 的 ORM 框架

延伸閱讀:
https://dotblogs.com.tw/dog0416/2016/06/12/030240
https://blog.miniasp.com/post/2009/03/02/Entity-Framework-Quick-Start-and-Leaning-Resources

(二) 目標

將DB Playground的所有與資料庫互動的Raw SQL操作方式改成ORM的操作方式

改寫後的專案檔案架構:
https://ithelp.ithome.com.tw/upload/images/20191013/20120331bBoFqfnFwJ.png

(三) 實作程式碼與流程

0. 宣告存取資料庫實體的物件

EF_Model.VocabularyEntity entity = new EF_Model.VocabularyEntity();

1.讀取所有學生

// 取得所有學生實體
EF_Model.student[] students = entity.student.ToArray();

// 顯示所有學生資訊
queryResultGrid.Rows.Clear();
foreach (EF_Model.student item in students)
{
    int newRowIndex = queryResultGrid.Rows.Add();
    queryResultGrid.Rows[newRowIndex].Cells["StudentID"].Value = item.StudentID;
    queryResultGrid.Rows[newRowIndex].Cells["Username"].Value = item.Username;
    queryResultGrid.Rows[newRowIndex].Cells["RealName"].Value = item.RealName;
    queryResultGrid.Rows[newRowIndex].Cells["Birthdate"].Value = item.Birthdate.GetValueOrDefault().ToString("yyyy-MM-dd");
}

2.新增學生

(1) 新增實體物件
Student student = new Student()

(2) 設定實體物件的欄位值
student.RealName = "泰D"

(3) 加到實體
entity.Student.add(student)

(4) 儲存並寫入DB
entity.SaveChanges()

// 新增學生實體
EF_Model.student insertStudent = getStudentFromField(true);
entity.student.Add(insertStudent);

try
{
    //  將新增的學生實體寫入資料庫
    entity.SaveChanges();
    queryStudentBtn.PerformClick();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

/// <summary>
/// 取得選擇的學生實體
/// </summary>
/// <returns></returns>
private EF_Model.student getStudentFromField(bool isAppend)
{
    EF_Model.student student;

    // 取得存在的學生實體 (用於修改、刪除)
    if (queryResultGrid.CurrentRow != null && !isAppend)
    {
        string currentStudentID = queryResultGrid.CurrentRow?.Cells["StudentID"].Value.ToString();
        student = entity.student.Where(item => item.StudentID == currentStudentID)
                                .FirstOrDefault();
    }
    // 產生新的學生實體 (用於新增)
    else
    {
        student = new EF_Model.student();

        student.StudentID = Guid.NewGuid().ToString();
        student.Password = SHAEncrypt(studentPasswordTextBox.Text);
    }

    student.RealName = studentNameTextBox.Text;
    student.Birthdate = studentBirthdatePicker.Value;
    student.Username = studentUsernameTextBox.Text;

    return student;
}

3. 修改學生

(1)取得實體
student = entity.student.Where(item => item.StudentID == currentStudentID
.FirstOrDefault();)

(2) 修改屬性值
student.RealName = "泰D"

(3) 儲存並寫入DB
entity.SaveChanges()

// 修改學生實體
EF_Model.student editStudent = getStudentFromField(false);
try
{
    // 將更新後的實體資料寫入資料庫
    entity.SaveChanges();
    queryStudentBtn.PerformClick();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

4. 刪除學生

(1) 取得實體
student = entity.student.Where(item => item.StudentID == currentStudentID)
.FirstOrDefault();

(2) 從所有實體中移除
entity.Student.Remove(student)

(3) 更新實體
entity.SaveChanges()

// 從所有學生實體當中移除學生
EF_Model.student student = getStudentFromField(false);
entity.student.Remove(student);
try
{
    // 將移除實體後的學生資訊更新至資料庫
    entity.SaveChanges();
    queryStudentBtn.PerformClick();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

上一篇
第二十六堂:英文單字測驗程式 - 學生帳號資料管理(5) - 修改學生與刪除學生 (認識實體)
下一篇
第二十八堂:英文單字測驗程式 - 單字測驗 - 亂數取得單字 (LIMIT、TOP、綜合練習)
系列文
從問題理解與活用SQL語法30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言