Entity Framework(四):使用DbModelBuilder API創建表結構


DbContext類有一個OnModelCreating方法,它用於流利地配置領域類到數據庫模式的映射。下面我們以fluent API的方式來定義映射。
首先,先將Product類注釋掉,重新編寫該類,重新編寫后的Product類:

復制代碼
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace EFFluentAPI.Model
 8 {
 9     public class Product
10     {
11         public int ProductNo { get; set; }
12 
13         public string ProductName { get; set; }
14 
15         public double ProductPrice { get; set; }
16     }
17 }
復制代碼

然后在數據庫上下文Context類中的OnModelCreating方法中使用fluent API來定義Product表的數據庫模式:

復制代碼
 1 using EFFluentAPI.Model;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Data.Entity;
 5 using System.Linq;
 6 using System.Text;
 7 using System.Threading.Tasks;
 8 
 9 namespace EFFluentAPI.EFContext
10 {
11     public class Context:DbContext
12     {
13         public Context()
14             : base("DbConnection")
15         { }
16 
17         public DbSet<Product> Products { get; set; }
18 
19         /// <summary>
20         /// 重新OnModelCreating方法
21         /// </summary>
22         /// <param name="modelBuilder"></param>
23         protected override void OnModelCreating(DbModelBuilder modelBuilder)
24         {
25             //映射到表Product,ProductNo和ProductName作為復合主鍵
26             modelBuilder.Entity<Product>().ToTable("Product").HasKey(p=>new {p.ProductNo,p.ProductName});
27             //ProductNo映射到數據表中的列名是Id
28             modelBuilder.Entity<Product>().Property(p => p.ProductNo).HasColumnName("Id");
29             modelBuilder.Entity<Product>().Property(p => p.ProductName)
30                 .IsRequired() //設置ProductName是必須的,即不能為null,默認是可以為null的
31                 .IsUnicode()  //設置ProductName列為Unicode字符,實際上默認就是Unicode字符,所以該方法可以不寫。
32                 .HasMaxLength(10); //設置ProductName列的最大長度是10
33             base.OnModelCreating(modelBuilder);
34         }
35     }
36 }
復制代碼

modelBuilder.Entity<Product>()會得到EntityTypeConfiguration類的一個實例。此外,使用fluent API的一個重要決定因素是我們是否使用了外部的POCO類,即實體模型類是否來自一個類庫。我們無法修改類庫中類的定義,所以不能通過數據注解來提供映射細節。這種情況下,我們必須使用fluent API。

什么是POCO?

POCO是指Plain Old Class Object,也就是最基本的CLR Class,在原先的EF中,實體類通常是從一個基類繼承下來的,而且帶有大量的屬性描述。而POCO則是指最原始的Class,換句話說這個實體的Class僅僅需要從Object繼承即可,不需要從某一個特定的基類繼承。主要是配合Code First使用。Code First則是指我們先定義POCO這樣的實體Class,然后生成數據庫。實際上現在也可以使用Entity Framweork Power tools將已經存在的數據庫反向生成POCO的Class(不通過edmx文件)。

程序運行后創建的數據庫如下圖所示:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM