EF框架的搭建(DataBase First)

一、EF的創建

使用EF進行數據庫開發的時候有兩個東西建:建數據庫(T_Persons),建模型類(Person)。EF的三種創建方法:
1.DataBase First(數據庫優先):先創建數據庫表,然後自動生成EDM文件,EDM文件生成模型類。簡單展示一下DataBase First 的使用。
2.Model First(模型優先):先創建Edm文件,Edm文件自動生成模型類和數據庫;
3.Code First(代碼優先):程序員自己寫模型類,然後自動生成數據庫。沒有Edm。

三種創建的區別

  1. DataBase First 簡單、方便,但是當項目大了之後會非常痛苦;
  2. Code First 入門門檻高,但是適合於大項目。
  3. Model First…… (不需要考慮)
    無論哪種First,一旦創建好了數據庫、模型類之後,後面的用法都是一樣的。業界都是推薦使用Code First,新版的EF中只支持Code First,因此我們這裏只講Code First。

二、DataBase First

  1. 首先在數據庫中創建好數據庫、數據表,以及表結構
  2. 在創建C#項目時,添加EF框架,選擇“ADO.NET 實體數據模型”
  3. 在實體數據模型嚮導中選擇“來自數據庫的EF設計器”
  4. 進行數據庫連接中“建立新的連接”
  5. 進行尋找連接目標數據庫,創建EF數據實體模型
    在這裏插入圖片描述

1.App.config:配置文件,裏面有連接數據庫字符串,EF的相關配置
2.StudentModel.edmx:EDM元數據文件
3.StudentModel.Context.cs:數據庫上下文類,可以理解爲是映射關係類
4.StudentMode.tt:實體類集合

EDM元數據

EDM設計器模式和XML結構
在這裏插入圖片描述

在這裏插入圖片描述

XML結構中明顯有三個類型節點,分別對應EDM中的存儲模型、概念模型、映射

實體文件

在StudentMode.tt文件裏面,可以找到實體文件和選擇的數據庫表的對應實體表
數據庫上下文類

namespace DBFirst
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    
    public partial class StudentManagerEntities : DbContext
    {
        public StudentManagerEntities()
            : base("name=StudentManagerEntities")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public virtual DbSet<Admin> Admin { get; set; }
        public virtual DbSet<Course> Course { get; set; }
        public virtual DbSet<Score> Score { get; set; }
        public virtual DbSet<Student> Student { get; set; }
    }
}

StudentModel.Context.cs集成自DbContext
DbContext-實體對象容器
作用:操作數據庫的工具,負責管理對象的CRUD(增、刪、改、查)操作,以及相應的事務及併發問題
特別注意:某個數據表的字段全部都是外鍵的時候,不會生成該表對應的實體類

使用EF查詢單表數據

在DbSet< T>對象中查詢符合條件的實體,一般用基類 IEnumerable<Student> 類型包含的兩個方法

IQueryable<Student> Where<Student>(Expression<Func<Student,bool>> predicate)
Student SingleOrDefault<Student>(Expression<Func<Student,bool>> predicate)
private void Form1_Load(object sender, EventArgs e)
        {
            StudentManagerEntities studentEF = new StudentManagerEntities();
            List<Student> list = studentEF.Student.ToList();
        }

使用EF實現CRUD

1. 添加數據

使用DbSet<T> 中的Add方法
然後使用DbContext的SaveChanges()方法

 Student stu = new Student()
                {
                     SName=txtName.Text.Trim(),
 SAge=int.Parse(txtAge.Text.Trim()),SEmail=txtEmail.Text.Trim(),            SSex=radioButton1.Checked?"男":"女"
                };
                studentEF.Student.Add(stu);//只是將實體對象添加到了數據庫上下文對應的對象集合中,而並非添加到了數據庫中了
                int res = studentEF.SaveChanges();//將數據庫上下文中的更改保存到數據庫中

2.修改數據

從DbContext中獲取實體
修改數據
使用DbContext的SavaChanges()方法

					if (radioButton1.Checked)
                    {
                        currentStu.SSex = "男";
                    }
                    else if (radioButton2.Checked)
                    {
                        currentStu.SSex = "女";
                    }
                    currentStu.SName = txtName.Text.Trim();
                    currentStu.SAge = int.Parse(txtAge.Text.Trim());
                    currentStu.SEmail = txtEmail.Text.Trim();
                    int res = entities.SaveChanges();
                    this.Close(); 

3.使用EF刪除

使用DbContext獲取實體
使用DbSet< T> 的Remove()方法
使用DbContext的SaveChanges()方法

 Student stu = studentEF.Student.Find(int.Parse(dataGridView1.SelectedRows[0].Cells["Id"].Value.ToString()));
                if (stu!=null)
                {
                    studentEF.Student.Remove(stu);
                    studentEF.SaveChanges();
                    RefreshStudent();
                }

官方文檔: https://docs.microsoft.com/zh-cn/ef/core/get-started/?tabs=netcore-cli

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章