1. 程式人生 > >.NET中微軟實體框架的資料訪問方法

.NET中微軟實體框架的資料訪問方法

介紹

本文的目的是解釋微軟的實體框架提供的三種資料訪問方法。網上有好幾篇關於這個話題的好文章,但是我想以一個教程的形式更詳細地介紹這個話題,這個教程對於開始學習實體框架及其方法的人來說是個入門。我們將逐步探索每個方法,通過這些方法,我們可以在應用程式中使用實體框架訪問資料庫和資料。我將使用實體框架版本6.2和.NETFramework 4.6。和Visual Studio 2017的教程。對於資料庫,我們將使用SQLServer。如果沒有安裝SQLServer,則可以使用本地資料庫。我將在本文中首先解釋資料庫和模型優先方法,並在下一篇文章中解釋程式碼優先方法和程式碼優先遷移。

實體框架

微軟實體框架是ORM(物件-關係對映)。維基百科的定義對於ORM和PITY非常簡單。

電腦科學中的物件關係對映(ORM、O/RM和O/R對映工具)是一種使用面向物件的程式語言在不相容型別系統之間轉換資料的程式設計技術。實際上,這將建立一個可以從程式語言中使用的“虛擬物件資料庫”。

作為一個ORM,實體框架是由Microsoft提供的資料訪問框架,它有助於在應用程式中建立物件和資料結構之間的關係。它是通過傳統的ADO.NET構建的,並作為ADO.NET上的包裝器。它是對ADO.NET的一種增強,它以更加自動化的方式提供資料訪問,從而減少了開發人員與連線、資料讀取器或資料集的鬥爭。它是對所有這些的抽象,對它所做的貢獻更為強大。開發人員可以對他所需要的資料、形式和數量有更多的控制權。沒有資料庫開發背景的開發人員可以利用實體框架和LINQ能力編寫優化查詢來執行DB操作。SQL或DB查詢執行將由後臺實體框架處理,它將處理可能發生的所有事務和併發問題。EntityFrameworkTutorial是一個網站,您可以通過它深入瞭解這個概念,並理解它的工作模型、體系結構等等。

實體框架方法

瞭解微軟實體框架提供的三種方法是非常常見的。三種方法如下:

  1. 模型優先
  2. 資料庫優先
  3. 程式碼優先

從資料模型類生成資料庫。

從現有資料庫生成資料模型類。

模型第一種方法說,我們有一個模型,該模型具有各種實體和關係/關聯,使用該模型,我們可以生成一個數據庫,最終將實體和屬性轉換為資料庫表,列和關係將轉換為外部分別是金鑰。

資料庫第一方法表示,我們已經有一個現有的資料庫,我們需要在我們的應用程式中訪問該資料庫。我們可以直接從資料庫建立實體資料模型及其關係,只需要幾次單擊即可開始從我們的程式碼訪問資料庫。所有實體,例如,類將由實體框架生成,實體框架可用於應用程式資料訪問層以參與DB操作查詢。

程式碼優先方法是EF的推薦方法,尤其是在從頭開始開發應用程式時。您可以預先定義POCO類,以及它們的關係,並通過在程式碼中定義結構來想象資料庫結構和資料模型的樣子。最後,實體框架將負責為您的POCO類和資料模型生成資料庫,並負責事務、歷史和遷移。

通過這三種方法,您可以完全控制在任何時間點按需要更新資料庫和程式碼。

模型優先

使用模型第一方法,開發人員可能不需要編寫任何程式碼來生成資料庫。實體框架提供了設計器工具,這些工具可以幫助您建立模型,然後從中生成資料庫。這些工具更多的是拖放控制元件,它們只需要輸入,比如實體名是什麼、應該具有什麼屬性、與其他實體如何相關等等。使用者介面是非常容易使用和有趣的。模型設計器(如果可以的話)將幫助您生成DDL命令,這些命令可以直接從Visual Studio或在您的資料庫伺服器上執行,以便從您建立的模型建立資料庫。這將建立一個EDMX檔案,該檔案儲存概念模型、儲存模型和兩者之間的對映資訊。要了解概念模型和儲存模型,可以參考本文介紹中所提供的連結。我能夠看到的唯一缺點是,完全刪除資料庫並重新建立資料庫將是這種方法的挑戰。

資料庫優先

當我們已經有一個現有的資料庫並且需要在我們的應用程式中訪問時,我們首先使用資料庫的方法。使用實體框架為現有資料庫建立資料訪問方法將幫助我們在解決方案中生成上下文和類,通過這些上下文和類我們可以訪問資料庫。這是模型第一種方法的反面。這裡,模型是通過資料庫建立的,我們可以完全控制在模型中包括哪些表,以及包括哪些儲存過程、函式或檢視。您的應用程式可能是一個子應用程式,它不需要大型資料庫的所有表或物件,因此您可以在這裡自由地控制應用程式中所需的內容和應用程式中不需要的內容。每當資料庫模式改變時,只需單擊設計器或實體資料模型即可輕鬆更新實體資料模型,這將負責對映並在應用程式中建立必要的類。

程式碼優先

使用程式碼第一方法,開發人員的重點只在程式碼上,而不是在資料庫或資料模型上。開發人員可以在程式碼本身中定義類及其對映,由於現在實體框架支援繼承,所以更容易定義關係。實體框架負責為您建立或重新建立資料庫,不僅如此,在建立資料庫時,還可以提供種子資料。例如,當建立資料庫時,您希望您的表具有主資料。首先使用程式碼,您可能沒有具有關係和模式的.edmx檔案,因為它不依賴於實體框架設計器及其工具,並且由於您是建立類和關係並管理資料庫的人,因此將對資料庫有更多的控制。出現了程式碼優先遷移的新概念,這使得程式碼優先方法更易於使用和遵循,但在本文中,我將不使用遷移,而是使用建立DB上下文和DB集類的舊方法,以便您瞭解隱藏的內容。程式碼優先方法還可以用於從現有資料庫生成程式碼,因此它基本上提供了兩種可以使用的方法。

行動中的實體框架方法

足夠的理論,讓我們從執行部分開始,一步一步地一步一步地探索和學習每一種方法。我將使用一個示例專案,並將其用於控制檯應用程式,以使用實體框架連線資料庫。我會用基本的樣本表來解釋這個概念。這裡的目的是學習概念並實現它,而不是建立一個大的應用程式。When you learn it, you can use the concepts with any large enterprise level application or any big database server which can have thousands of tables. 所以,我們將遵循接吻策略,並在這裡保持簡單。

模型優先

  1. Create a simple .NET Framework console application by opening your visual studio and choosing the console application template. We can choose any application type like a web application that could be ASP.NET web forms, MVC or Web API or windows application/WPF application. You can give a name to the project and solution of your choice.

  2. We’ll have Program.cs, the only class and App.config in our project.

  3. Right-click the project and click on add a new item, this will open the window to add a new item, just go to Data as shown in below image and choose ADO.NET Entity Data Model as shown in the following image. Give it a name. For example, EFModel and click on Add.

  4. Once you click add, you’ll be shown to choose Model Contents, and this is the place where you choose what approach you want to use for data access out of the three EF approaches. So, choose Empty EF Designer because we would be using model first approach and create a model from scratch.

  5. Once you click "Finish", you see the empty designer window that is the .edmx file. The name of the .edmx file in solution is the name that we provided while adding the EF designer model. In the toolbox, you see the tools available that you could use to create entities and associations between them.

  6. Drag and drop the Entity tool from the toolbox into the designer. It will create an empty entity as shown below with one property named Id, saying it is a primary key. Here you can rename the entity and add more scalar properties.

  7. Right click on entity created and add a new scalar property as shown in the following image. Rename the name of the entity from Entity1 to Student. You can rename the entity by double-clicking on the entity name and right click and rename the entity.

  8. Name the scalar property as "Name".

  9. In an analogous way add a new entity named Class and add a new property named ClassName. We here are trying to create a student and a class relationship where a class can have multiple students. So, we have an option to choose Association from toolbox as shown below and drag the Association tool from Class to Student and it showed 1 to many relationship.

  10. We are not adding more entities and try to understand the basic functionality with these two entities. Right click on the designer and click on "Generate Database from Model…" option to generate the scripts.

  11. Once you click on "Generate Database from Model…" option, you’ll be asked to choose data connection as shown in the following window. You can choose a new connection or an existing one. I’ll choose a new connection but before that, I’ll create an empty database on my SQL server so that I do not have to modify my scripts to provide a database name. By default, the generated scrips create tables in the master database if DB name is not specified.

  12. Open your SQL Server and create a new database and name it as per your choice. I am naming it StudentDB as shown in the following images.

  13. Coming back to the window where we needed to provide the connection details. Choose your data source and server name as shown in the following image. The server name should be the server where you created the empty database. Now in the selecting database option, expand the dropdown and you should see your database name. Select the database name.

  14. Once you select the database name, a connection string would be generated as shown below and it will say that the connection string would be saved I the App.Config file with the name EFModelContainerEFModelContainer is the name of the connection string. Since it is an EF generated connection string, you see it has the information about EF CSDL, MSL and SSDL files as well that would be present in our application. Click Next to proceed.

  15. Next step is to choose your Entity Framework version. We’ll use 6.x i.e. it will automatically pick the latest stable version with EF6. Click Next.

  16. As a last step of the wizard, you’ll see the needed SQL scripts created for us. You can choose to rename the scripts but by default, it takes the name as <model name>.edmx.sql. I’ll leave it as it is and click Finish to proceed.

  17. You’ll see the script located in solution explorer now. Double click to open it and it opens in a window where you have an option to directly execute it.

  18. Before executing the scripts let’s first install Entity Framework latest stable version from the Nuget package manager. It is very simple to do. Go to Tools in Visual Studio, then choose NuGet Package Manager->Package Manager Console as shown in the following image.

  19. The NuGet Package Manager console window will be opened at the bottom of Visual Studio by default. Now choose the project for which the Entity Framework package needs to be installed. And in the command that says PM> type Install-Package EntityFramework and press enter. We do not specify the version of entity framework as we want the latest stable package should be downloaded and added to our project as a DLL reference.

  20. Once done with installing Entity Framework, go back to the script window and on the top left, you see the button to execute the scripts as shown below. Press the button to execute the scripts.

  21. Once you click on Execute, a new window will show up asking server and database details. Fill in the details specific to your server and database as shown below and click Connect.

  22. Once done, go to your database server and you’ll see the tables are created for our database StudentDB. The names of the tables are pluralized, and Student table has a foreign key reference to Classes table and the foreign key is automatically created named Class_Id referencing Classes table. It is magical, isn’t it?

  23. In our solution explorer, we see the .edmx file and the context classes created and model classes for Student and Class entities. This is all done in the background by EF designer. So, till now we did not write a single code and got all the code generated by EF.

  24. Open the EFModel.Context.cs class file and we see the name of the DbContext class that got generated is EFModelContainer. Remember that is the name of our connection string stored in App.Config. The name of the context class has to be the same as connection string name for EF to know the relation. So, you can have multiple DB context classes in the same solution with different names and pointing to different connection strings. You can explore more on DbContext class and what other ways you can make its relation to the connection string in the config file. One another way is to call its base constructor by passing name of the connection string as a parameter to its parameterized constructor. But for the sake of understanding, we’ll stick to this implementation.

  25. Now it’s time to test our implementation and check if the entity framework is actually working and helping us in database operations or not. So, in the Program.cs class’s Main method we’ll try to write some code that saves a new class for us in the database. Create a new object of EFModelContainer and in the container, we get the entity classes collection coming from DbContext. Add a new Class. The class is the name of the entity class generated for us via designer. And name the class as "Nursery". We do not have to specify the id attribute for the class, as EF will automatically handle this and provide an Id to a newly added record. The code to add a new class named "Nursery" is shown in the following image. The container.SaveChanges statement is the statement when executed will add a new record in the database for us.

  26. Just run the application and let the main method code execute. Once done, go to your database and check the Classes table, you’ll see a new record is added in the Classes table with the class name "Nursery" which is what we provided while wanted to add a record. So, it works ?. Notice the Id that is auto generated by entity framework.

  27. Now, let’s try something new and try to add a new class but this time with students. We have a relationship of class with students that is a class can have many students and a student will belong to one class. Check the created model classes for Student and Class if you want to explore how the relationship is maintained in the classes. So, this time, we’ll add a new class and add some students to that class. Entity Framework should automatically add these students to the Students table and make the relationship with the Class table. Following is the simple self-explanatory code for doing this.
    static void Main(string[] args)
    {
        EFModelContainer container = new EFModelContainer();
        ICollection<Student> students = new List<Student>
        {
            new Student() { Name = "Mark" },
            new Student() { Name = "Joe" },
            new Student() { Name = "Allen" }
        };
    
        container.Classes.Add(new Class() {ClassName = "KG", Students = students });
        container.SaveChanges();
    }
    

    In the above code, we create an EFModelContainer object and a list of Students by adding three students into it. Now add a new class to the container object, just like we did in the last example and assign students to the Students property of the Class object. Last but not the least, container.SaveChanges().

  28. Run the code and go to the database. Check the Classes table and see a newly created class row with name "KG" that we supplied from the code.

Now, go to the Students table and we got three students created there those we supplied from code and check the Class_Id column that has the foreign key reference to the newly created class with Id 2. Amazing ?

Like this, you can perform complex queries and other CRUD operations on your database by writing simple code. Try to perform more operations like editing, deleting fetching the records to understand more. Let’s move to our next topic that is database first approach with Entity Framework.

Database First

  1. Like we did in model first approach, create a new console application and name it EF_DBF.

  2. The second step is to add a new ADO.NET Entity Data Model to this project. Name it of your choice. I named it ModelDBF.

  3. Now, from the choose model window, we’ll choose the option of EFDesigner from the database, this will help us to create an entity framework designer from the existing database.

  4. Next, choose the connection for the database. For example, provide the details on the wizard for your existing database. I’ll take the database we created with our model first approach i.e. StudentDB. Once we choose the database, we see the entity framework connection string and the name of the connection string to be saved in App.Config i.e. StudentDBEntities. You can also change it if you want. Click Next.

  5. Choose the EF version. I already explained the meaning of 6.x. We’ll choose the same and click Next.

  6. Now in this step, you would be shown all the database objects related to the database you selected initially, and it is your choice to include or exclude the objects you need. The objects could be tables, views or stored procedures. Since we do not have views and stored procedures, we’ll only choose our two tables as shown in the following image. Since we already have the table’s name in pluralized forms, I do not want to complicate this by again pluralizing it and appending one more ‘s’ to my entity classes, so I unchecked that option of pluralizing the entity names. Provide model namespace or leave it as it is with the default name provided and click Finish.

  7. Once you click Finish, you see the entities created in the EF designer for the database objects we selected from the database. We notice that it is like what we had when we manually created the entities and generated a database out of it. This EF designer also takes care of foreign key relationship and shows the one to many association between class and student entities.

  8. Time to add Entity Framework package like we did in the first approach discussed. Make sure you choose the right project, for example,the current project where you need to add EF. Type the command in package manager Console and press enter.

  9. Now, when we open the generated ModelDBF.Context.cs, we see the name of the partial class as StudentDBEntities i.e. the name of the connection string we got stored in App.Config. I have already explained the logic behind it in the last section.

  10. Time to see some action now. Add the code below to the Program.cs Main() method.
    static void Main(string[] args)
     {
         StudentDBEntities container = new StudentDBEntities();
         ICollection<Students> students = new List<Students>
         {
             new Students() { Name = "Harry" },
             new Students() { Name = "Jane" },
             new Students() { Name = "Nick" }
         };
    
         container.Classes.Add(new Classes() { ClassName = "Class 1", Students = students });
         container.SaveChanges();
    
         container.Students.Add(new Students() {Class_Id = 1, Name = "Ben"});
         container.SaveChanges();
    
     }
    

    In the above code, we are trying to create an object of StudentDBEntities class. For example, our context class and a collection of students to be added to our database. To check the relationship is working fine or not, we’ll add a new class named "Class 1" and assign the Students property to our students collection and SaveChanges() again to check if individual student insertion is working or not, we’ll add a new student named "Ben" to the Students model and assign the class id to 1. For example, the existing class we have in database and SaveChanges(). Put a breakpoint in Main method and press F5.

  11. When the application runs it will hit the breakpoint. Navigate through the statements by pressing F10 and stop at line 24 i.e. before we add a new student. Since we already executed the code for saving changes for newly added class. Let’s go to the database and check.

  12. In the database, we see the newly added class has a new row in Classes table with ID 3.

    And in the Students table, we see that three students that we added from code got inserted in the table with the class id as 3 i.e. the newly created class.

  13. Now get back to Visual Studio and execute the line for adding a new student.

完成後,檢查資料庫,我們看到一個新學生,名字是“Ben”,新增到我們的學生表中,具有Class_Id 1,我們在程式碼中分配。

我們看到我們的資料庫第一種方法也很好用。再次,您可以嘗試在您的程式碼中的其他DB操作,並與程式碼玩更多的探索。讓我們轉到程式碼第一方法。

結論

  在本文中,我們仔細研究瞭如何利用實體框架方法,並根據需要使用這些框架。我使用基本的控制檯應用程式來解釋這些概念,但是這些概念可以用於任何使用WebAPI、ASP.NET專案或MVC專案的企業級應用程式中。我們簡要地討論了使用的方法的優點和缺點,並嘗試建立小樣本應用程式,以檢視那些工作。實體框架有很多需要探索的地方。例如,底層架構是什麼,架構如何工作,事務管理,載入等等。我個人認為EF是最好和最強大的ORM之一,可以與任何.NET應用程式無縫整合。在本文中,我故意跳過程式碼第一方法和程式碼第一遷移,因為這會使文章冗長。在下一篇文章中,我將解釋在實體框架中使用實體框架和程式碼第一遷移的程式碼第一方法。