2020年9月27日 星期日

Entity Framework Core - 反向工程 建立 Entity Model建立 Entity Model

Entity Framework Core - 反向工程 建立 Entity Model建立 Entity Model

在 Entity Framework Core - 建立練習使用的 Contoso University 資料庫 內,已經說明了如何建立起 Contoso 大學的資料庫架構與相關測試資料,現在,將會需要建立起 .NET C# 使用的 Entity Model,這裡提到的 Entity ,就是 Entity Framework 內的 Entity 這個名詞。想要在 C# 內建立一個類別,可以透過這個類別來存取 資料庫 內的紀錄,需要讓這個類別繼承 DbContext 類別,並且宣告 DbSet 屬性 ,實體類型,這裡的泛型型別 T ,將會對應到資料庫內的 Table 表格。

現在開始來練習這個開發過程,這樣的技術稱之為 Entity Framework Core - 反向工程,在此將會使用 Console 專案來做為示範。

建立練習專案

  • 打開 Visual Studio 2019
  • 點選 [建立新的專案] 按鈕
  • 在 [建立新專案] 對話窗內,選擇 [主控台應用程式 (.NET Core)] 專案樣板
  • 在 [設定新的專案] 對話窗內,於 [專案名稱] 欄位內輸入 EFCoreReverseEngineering
  • 點選 [建立] 按鈕,以便開始建立這個專案

加入 Entity Framework Core 要使用到的 NuGet 套件

  • 滑鼠右擊專案內的 [相依性] 節點
  • 選擇 [管理 NuGet 套件]
  • 點選 [瀏覽] 標籤分頁頁次
  • 在 [搜尋] 文字輸入盒內,輸入 [Microsoft.EntityFrameworkCore.SqlServer]
  • 點選 [安裝] 按鈕以便安裝這個套件
  • 在 [搜尋] 文字輸入盒內,輸入 [Microsoft.EntityFrameworkCore.Tools]
  • 點選 [安裝] 按鈕以便安裝這個套件

使用反向工程來產生 Entity Framework 要用到的 Entity 模型相關類別

  • 切換到 [套件管理器主控台] 視窗

    若沒有看到 [套件管理器主控台] 視窗,點選功能表 [工具] > [NuGet 套件管理員] > [套件管理器主控台]

  • 在 [套件管理器主控台] 輸入底下內容

Scaffold-DbContext "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=School" Microsoft.EntityFrameworkCore.SqlServer -StartupProject EFCoreReverseEngineering -Project EFCoreReverseEngineering -OutputDir Models -f

現在 Entity Model 相關資料已經建立完成,底下是輸入 [Scaffold-DbContext] 指令的相關執行內容

每個封裝均由其擁有者提供授權給您。NuGet 對於協力廠商封裝不負任何責任,也不提供相關的任何授權。某些封裝可能包含須由其他授權控管的相依項目。請遵循封裝來源 (摘要) URL 決定有無任何相依項目。

套件管理員主控台主機版本 5.7.0.6726

輸入 'get-help NuGet' 可查看所有可用的 NuGet 命令。

PM> Scaffold-DbContext "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=School" Microsoft.EntityFrameworkCore.SqlServer -StartupProject EFCoreReverseEngineering -Project EFCoreReverseEngineering -OutputDir Models -f
Build started...
Build succeeded.
PM>

請查看 Visual Studio 內的方案總管視窗內,將會看到自動建立了一個方案資料夾,稱之為 [Models],在這個資料夾內存在著許多檔案。

Entity Framework DbContext

現在來打開 [Department.cs] 這個檔案,從名稱可以看的出來,這裡指的就是 SQL Server 資料庫上的 Department 資料表 Table。

using System;
using System.Collections.Generic;

namespace EFCoreReverseEngineering.Models
{
    public partial class Department
    {
        public Department()
        {
            Course = new HashSet<Course>();
        }

        public int DepartmentId { get; set; }
        public string Name { get; set; }
        public decimal Budget { get; set; }
        public DateTime StartDate { get; set; }
        public int? Administrator { get; set; }

        public virtual ICollection<Course> Course { get; set; }
    }
}

另外,查看 SQL Server 上的 Department 資料表的結構定義,其宣告如下:

CREATE TABLE [dbo].[Department] (
    [DepartmentID]  INT           NOT NULL,
    [Name]          NVARCHAR (50) NOT NULL,
    [Budget]        MONEY         NOT NULL,
    [StartDate]     DATETIME      NOT NULL,
    [Administrator] INT           NULL,
    CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED ([DepartmentID] ASC)
);

透過 Department 資料表的綱要宣告,可以來理解透過反向工程所產生的 Entity Model 為什麼是這樣宣告的。

因此,在資料庫上的每個資料表,都會在 [Models] 資料夾內,產生一個類別檔案,另外,也會針對這個資料庫,產生一個 [SchoolContext.cs] 檔案,其內容如下。

這裡建立了一個 [SchoolContext] 類別,這個類別將會指向 SQL Server 上的 [School] 資料庫,也就是說,想要對這個資料庫進行任何操作:新增、讀取、修改、刪除,都可以透過這個 [SchoolContext] 類別來做到,因此,對於使用 Entity Framework Core 的開發者,只需要會使用 C# 程式碼,就可以進行資料庫的紀錄存取操作了。

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace EFCoreReverseEngineering.Models
{
    public partial class SchoolContext : DbContext
    {
        public SchoolContext()
        {
        }

        public SchoolContext(DbContextOptions<SchoolContext> options)
            : base(options)
        {
        }

        public virtual DbSet<Course> Course { get; set; }
        public virtual DbSet<CourseInstructor> CourseInstructor { get; set; }
        public virtual DbSet<Department> Department { get; set; }
        public virtual DbSet<OfficeAssignment> OfficeAssignment { get; set; }
        public virtual DbSet<OnsiteCourse> OnsiteCourse { get; set; }
        public virtual DbSet<Outline> Outline { get; set; }
        public virtual DbSet<Person> Person { get; set; }
        public virtual DbSet<StudentGrade> StudentGrade { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                optionsBuilder.UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=School");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Course>(entity =>
            {
                entity.Property(e => e.CourseId)
                    .HasColumnName("CourseID")
                    .ValueGeneratedNever();

                entity.Property(e => e.DepartmentId).HasColumnName("DepartmentID");

                entity.Property(e => e.Title)
                    .IsRequired()
                    .HasMaxLength(100);

                entity.HasOne(d => d.Department)
                    .WithMany(p => p.Course)
                    .HasForeignKey(d => d.DepartmentId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_Course_Department");
            });

            modelBuilder.Entity<CourseInstructor>(entity =>
            {
                entity.HasKey(e => new { e.CourseId, e.PersonId });

                entity.Property(e => e.CourseId).HasColumnName("CourseID");

                entity.Property(e => e.PersonId).HasColumnName("PersonID");

                entity.HasOne(d => d.Course)
                    .WithMany(p => p.CourseInstructor)
                    .HasForeignKey(d => d.CourseId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_CourseInstructor_Course");

                entity.HasOne(d => d.Person)
                    .WithMany(p => p.CourseInstructor)
                    .HasForeignKey(d => d.PersonId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_CourseInstructor_Person");
            });

            modelBuilder.Entity<Department>(entity =>
            {
                entity.Property(e => e.DepartmentId)
                    .HasColumnName("DepartmentID")
                    .ValueGeneratedNever();

                entity.Property(e => e.Budget).HasColumnType("money");

                entity.Property(e => e.Name)
                    .IsRequired()
                    .HasMaxLength(50);

                entity.Property(e => e.StartDate).HasColumnType("datetime");
            });

            modelBuilder.Entity<OfficeAssignment>(entity =>
            {
                entity.HasKey(e => e.InstructorId);

                entity.Property(e => e.InstructorId)
                    .HasColumnName("InstructorID")
                    .ValueGeneratedNever();

                entity.Property(e => e.Location)
                    .IsRequired()
                    .HasMaxLength(50);

                entity.Property(e => e.Timestamp)
                    .IsRequired()
                    .IsRowVersion()
                    .IsConcurrencyToken();

                entity.HasOne(d => d.Instructor)
                    .WithOne(p => p.OfficeAssignment)
                    .HasForeignKey<OfficeAssignment>(d => d.InstructorId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_OfficeAssignment_Person");
            });

            modelBuilder.Entity<OnsiteCourse>(entity =>
            {
                entity.HasKey(e => e.CourseId);

                entity.Property(e => e.CourseId)
                    .HasColumnName("CourseID")
                    .ValueGeneratedNever();

                entity.Property(e => e.Days)
                    .IsRequired()
                    .HasMaxLength(50);

                entity.Property(e => e.Location)
                    .IsRequired()
                    .HasMaxLength(50);

                entity.Property(e => e.Time).HasColumnType("smalldatetime");

                entity.HasOne(d => d.Course)
                    .WithOne(p => p.OnsiteCourse)
                    .HasForeignKey<OnsiteCourse>(d => d.CourseId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_OnsiteCourse_Course");
            });

            modelBuilder.Entity<Outline>(entity =>
            {
                entity.Property(e => e.OutlineId).HasColumnName("OutlineID");

                entity.Property(e => e.CourseId).HasColumnName("CourseID");

                entity.Property(e => e.Title)
                    .IsRequired()
                    .HasMaxLength(100);

                entity.HasOne(d => d.Course)
                    .WithMany(p => p.Outline)
                    .HasForeignKey(d => d.CourseId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_Outline_Course");
            });

            modelBuilder.Entity<Person>(entity =>
            {
                entity.Property(e => e.PersonId).HasColumnName("PersonID");

                entity.Property(e => e.EnrollmentDate).HasColumnType("datetime");

                entity.Property(e => e.FirstName)
                    .IsRequired()
                    .HasMaxLength(50);

                entity.Property(e => e.HireDate).HasColumnType("datetime");

                entity.Property(e => e.LastName)
                    .IsRequired()
                    .HasMaxLength(50);
            });

            modelBuilder.Entity<StudentGrade>(entity =>
            {
                entity.HasKey(e => e.EnrollmentId);

                entity.Property(e => e.EnrollmentId).HasColumnName("EnrollmentID");

                entity.Property(e => e.CourseId).HasColumnName("CourseID");

                entity.Property(e => e.Grade).HasColumnType("decimal(3, 2)");

                entity.Property(e => e.StudentId).HasColumnName("StudentID");

                entity.HasOne(d => d.Course)
                    .WithMany(p => p.StudentGrade)
                    .HasForeignKey(d => d.CourseId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_StudentGrade_Course");

                entity.HasOne(d => d.Student)
                    .WithMany(p => p.StudentGrade)
                    .HasForeignKey(d => d.StudentId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_StudentGrade_Student");
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}



 

2020年9月26日 星期六

在執行緒內拋出例外異常,可否捕捉到

在執行緒內拋出例外異常,可否捕捉到

許多人在使用 C# 非同步程式設計的 TAP 模式時候,往往會聽到這樣的強調內容:當設計 非同步方法,也就是在方法前面加上 async 修飾詞,而該方法的回傳值需要為 Task 或者 Task<T>,千萬不要把這個非同步方法的回傳值宣告為 void,因為,這樣的宣告方式,僅適用於有事件訂閱的非同步委派方法內使用。

可是,往往大家在設計非同步方法的時候,都僅會在非同步方法前面加入 async 修飾詞,而將該非同步方法的回傳值宣告為 void;就是因為回傳值為 void,因此,當要呼叫這個非同步方法的時候,就僅能夠直接呼叫該非同步方法,而不能使用 await 關鍵字 (這是因為該非同步方法的回傳值必須是一個 Task 型別的物件,因為,await 之後,要接著一個 Task 物件,這樣才能等待)。

接著,更可怕的事情就發生了,因為這樣的呼叫方式,造成了射後不理的情況,也因為如此,也就無法使用 try...catch 敘述來捕捉這樣的非同步方法的例外異常。為了要讓大家更清楚問題在哪裡,因此,底下的程式碼將會使用執行緒來說明。

首先,在主執行緒內,故意拋出例外異常 Exception,並且使用 try ... catch 敘述來捕捉這個例外異常,這樣的寫法是標準作法,理所當然會捕捉到例外異常,而不會造成處理程序崩潰;不過,接下來使用 try...catch 將建立一個執行緒,等候三秒鐘之後,拋出例外異常,最後啟動該執行緒這樣的過程都包起來,因此,在程式執行後的三秒鐘後,並無法成功攔截捕捉到例外異常,而是造成 Process 崩潰,也就是說,在該執行緒的外面,是無法使用 try...catch 敘述來捕捉到該執行緒內所產生的任何例外異常錯誤。

static void Main(string[] args)
{
    Console.WriteLine($"Main Thread Id :" +
       $"{Thread.CurrentThread.ManagedThreadId}");
    try
    {
        throw new Exception("Capture Main Exception");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
 
    try
    {
        Thread thread = new Thread(() =>
        {
            Console.WriteLine($"New Thread Id :" +
                $"{Thread.CurrentThread.ManagedThreadId}");
            Thread.Sleep(3000);
            throw new Exception("Oh Oh");
        });
        thread.Start();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
 
 
}


 

2020年9月25日 星期五

在 .NET C# 環境中,要存取靜態變數或者區域變數,是否都是同樣的存取速度

 

在 .NET C# 環境中,要存取靜態變數或者區域變數,是否都是同樣的存取速度

當在進行多執行緒程式設計的時候,往往會需要能夠讓多執行緒可以同時來存取一個共用的資源,也許會利用這個共用資源做為要回傳執行緒執行結果之用;可是,你知道當 .NET C# 程式在進行靜態變數或者區域變數(也就是該變數通常位於某個函式內所宣告的變數)的時候,存取區域變數的執行速度,會優於靜態全域變數,而到底差了多少?

為了要了解這個問題,特別撰寫底下的程式碼,連續存取靜態變數與區域變數數次,這裡將會執行 int.MaxValue 次,看看執行結果,不過,這裡的執行結果將會是在 Release 模式下所測試出來的結果。

Access Static : 3660ms
Access Static : 3593ms
Access Static : 3625ms
Access Local : 1705ms
Access Local : 1653ms
Access Local : 1692ms

可以看到上述的執行及果,對於存取靜態變數的時候,在這個範例將需要花費 359ˇˇ~3660 ms 之間,不過,對於存取區域變數的時候,可以看的出來,存取速度明顯快了許多,大約為 1692 ~1705 ms 之間。

因此,若要在大量迴圈到要存取變數的時候,建議不要使用靜態變數,若有需要,可以將靜態變數設定為區域變數,以便增快執行速度。

class Program
{
    static int staticInt = 0;
    static void Main(string[] args)
    {
        int localInt = 0;
        StaticObjectAccess();
        StaticObjectAccess();
        StaticObjectAccess();
        LocalObjectAccess(localInt);
        LocalObjectAccess(localInt);
        LocalObjectAccess(localInt);
    }
 
    private static void LocalObjectAccess(int localInt)
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        for (int i = 1; i < int.MaxValue; i++)
        {
            if (i % 2 == 0)
                localInt++;
            else
                localInt--;
        }
        stopwatch.Stop();
        Console.WriteLine($"Access Local : {stopwatch.ElapsedMilliseconds}ms");
        return;
    }
 
    private static void StaticObjectAccess()
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        for (int i = 1; i < int.MaxValue; i++)
        {
            if (i % 2 == 0)
                staticInt++;
            else
                staticInt--;
        }
        stopwatch.Stop();
        Console.WriteLine($"Access Static : {stopwatch.ElapsedMilliseconds}ms");
        return;
    }
}





2020年9月21日 星期一

建立與查看Contoso 大學資料庫的 ERD Entity-Relationship Diagram

 

建立與查看Contoso 大學資料庫的 ERD Entity-Relationship Diagram

在上一篇文章 Entity Framework Core - 建立練習使用的 Contoso University 資料庫 中,已經說明如何在開發電腦環境中,建立一個測試用的資料庫,並且該資料庫內也產生了許多測試紀錄。可是,在這個資料庫內,這些資料表 Table 之間的關聯為何? 也就是在進行關聯式資料庫設計時候,經常會用到的 設計時候,ERD Entity-Relationship Diagram 是呈現甚麼內容? 在這篇文章中,將會說明如何得到這方面的資訊。

安裝 SQL Server Management Studio (SSMS)

使用 SQL Server Management Studio (SSMS) 產生 ERD

  • 安裝好 SQL Server Management Studio (SSMS) 之後,請打開這個應用程式

  • 首先會看到 [連線至伺服器] 對話窗

  • 請在 [伺服器名稱] 內,輸入 (localdb)\.

  • 最後,點選 [連線] 按鈕

  • 成功連線之後,將會顯示 [物件總管] 視窗

  • 請展開 [物件總管] 視窗內的 [(localdb.)] > [資料庫] > [School] 節點

  • 滑鼠右擊 [資料庫圖表] 節點,從彈出功能表選取 [新增資料庫圖表] 選項

  • 第一次將會出現 [此資料庫沒有使用資料庫圖表所需的一或多個支援物件。您要建立它們嗎?] 訊息

  • 點選 [是] 按鈕

  • 此時將會出現 [加入資料表] 對話窗

  • 請將全部資料表都選取起來

    想要全部選取,可以先點選第一個資料表 (Course),接著按下 [Shift] 按鍵,點選最後一個資料表(StudentGrade)

  • 最後,點選 [加入] 按鈕

  • 若這些資料表沒有正常排列顯示,請在空白處,使用滑鼠右擊,選擇 [排列資料表],這樣就會看到這個資料庫所以資料表之間的關聯 ERD,哪些是 一對一關係、一對多關係、多對一關係、多對多關係









Entity Framework Core - 建立練習使用的 Contoso University 資料庫

 

Entity Framework Core - 建立練習使用的 Contoso University 資料庫

今年將會撰寫許多關於 Entity Framework Core 的設計與使用說明文章,不過,當想要實際進行演練這些 Entity Framework Core 的用法,還是需要有個範例資料庫,並且該資料庫內最好已經具備了許多測試資料;在這裡,將會準備 Contoso University 資料庫 這個範例資料庫,因此,接下來就來說明如何安裝這個練習用的資料庫到讀者的開發電腦上。

使用 VS2019 匯入資料庫

  • 開啟 [Visual Studio 2019]

  • 選擇對話窗右下方的 [不使用程式碼繼續(W)] 連結

  • 點選 Visual Studio 2019 功能表的 [檢視] > [SQL Server 物件總管] 選項

    SQL Server 物件總管

  • 在 [SQL Server 物件總管] 視窗內,展開 [SQL Server] 節點,便會 [(localdb)\MSSQLLocalDB] 這個資料庫服務

  • 滑鼠右擊剛剛看到的 localdb 節點,選擇 [新增查詢] 功能表選項

  • 此時,將會顯示一個 [SQLQuery1.sql] 視窗

  • 請使用瀏覽器打開這個連結 Contoso University 資料庫,接這些內容複製到系統的剪貼簿內

  • 切換到 [SQLQuery1.sql] 視窗內,把這些內容貼到該視窗內

  • 點選該視窗標籤下方的綠色三角形,執行這些 SQL 敘述

    這個 Contoso University 資料庫 SQL 敘述,將會先把原先的 School 資料庫刪除掉 (可以從上圖的第 9~11 行看到這些 SQL 敘述) ,接著,將會建立 School 資料庫建立起來,並且建立相關資料表與產生測試資料紀錄到資料庫內。

    若執行完成之後,可以滑鼠右擊 [SQL Server 物件總管] 內的 localdb 節點,選擇 [重新整理]

確認練習用的資料庫已經建立完成

  • 請在 [SQL Server 物件總管] 視窗內的 [(localdb)\MSSQLLocalDB] > [資料庫] 節點內,找到 [School] 資料庫節點

  • 展開這個 [School] 節點,便可以看到最新產生的練習用資料庫了