EF CodeFirst系列(5)---FluentApi

来源:https://www.cnblogs.com/wyy1234/archive/2018/09/18/9670529.html
-Advertisement-
Play Games

FluentApi總結 1.FluentApi簡介 EF中的FluentApi作用是通過配置領域類來覆蓋預設的約定。在EF中,我們通過DbModelBuilder類來使用FluentApi,它的功能比數據註釋屬性更強大。 使用FluentApi時,我們在context類的OnModelCreatin ...


FluentApi總結

1.FluentApi簡介

  EF中的FluentApi作用是通過配置領域類來覆蓋預設的約定。在EF中,我們通過DbModelBuilder類來使用FluentApi,它的功能比數據註釋屬性更強大。

使用FluentApi時,我們在context類的OnModelCreating()方法中重寫配置項,一個慄子:

public class SchoolContext: DbContext 
{

    public DbSet<Student> Students { get; set; }
        
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Write Fluent API configurations here

    }
}

  我們可以把FluentApi和數據註釋屬性一起使用,當FluentApi和數據註釋屬性都配置了同一個項時,採用FluentApi中的配置。

在EF6中FluentApi可以配置領域類的以下幾個方面,下表也列出了一些常用的FluentApi方法及其作用:

配置Fluent API 方法作用
架構相關配置 HasDefaultSchema() 資料庫的預設架構
ComplexType() 把一個類配置為複雜類型
實體相關配置 HasIndex() 實體的的索引
HasKey() 實體的主鍵(可其實現複合主鍵,[Key]在EF core中不能實現複合主鍵)
HasMany() 1對多的或者 多對多關係 
HasOptional() 一個可選的關係,這樣配置會在資料庫中生成一個可空的外鍵
HasRequired() 一個必有的關係,這樣配置會在資料庫中生成一個不能為空的外鍵
Ignore() 實體或者實體的屬性不映射到資料庫
Map() 設置一些優先的配置
MapToStoredProcedures() 實體的CUD操作使用存儲過程
ToTable() 為實體設置表名
屬性相關配置 HasColumnAnnotation() 給屬性設置註釋
IsRequired() 在調用SaveChanges()方法時,屬性不能為空
IsOptional() 可選的,在資料庫生成可空的列
HasParameterName() 配置用於該屬性的存儲過程的參數名
HasDatabaseGeneratedOption() 配置資料庫中對應列的值怎樣生成的,如計算,自增等
HasColumnOrder() 配置資料庫中對應列的排列順序
HasColumnType() 配置資料庫中對應列的數據類型
HasColumnName() 配置資料庫中對應列的列名
IsConcurrencyToken() 配置資料庫中對應列用於樂觀併發檢測

2.實體相關配置

1.實體簡單配置

直接上慄子:

我們新建一個EF6Demo的控制台應用程式,添加Student和Grade實體,以及上下文類SchoolContext,代碼如下:

    //學生類
    public class Student
    {
        public int StudentId { get; set; }
        public string StudentName { get; set; }
        public string StudentNo { get; set; }
        public virtual Grade Grade{get;set;}
    }
   //年級類
   public class Grade
    {
        public int GradeId { get; set; }
        public string GradeName { get; set; }
        public virtual ICollection<Student> Students { get; set; }
    }
    //上下文類
    public class SchoolContext:DbContext
    {
        public SchoolContext() : base()
        {
        }
        public DbSet<Student> Students { get; set; }
        public DbSet <Grade> Grades { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
           
            modelBuilder.HasDefaultSchema("Admin");//添加預設架構名
            modelBuilder.Entity<Student>().ToTable("StudentInfo");
            modelBuilder.Entity<Grade>().ToTable("GradeInfo","NewAdmin");//設置表名和架構
        }
    }

在Main函數中執行代碼:

    class Program
    {
        static void Main(string[] args)
        {
            using (SchoolContext context=new SchoolContext())
            {
                context.Students.Add(new Student() { StudentId = 1, StudentName = "Jack" });
                context.SaveChanges();
            }
        }
    }

這時在內置的SqlServer中生成資料庫,如下圖所示,我們看到Student表名為StudentInfo,架構是Admin;Grade表名是GradeInfo,架構是NewAdmin,覆蓋了預設的約定(預設表名為dbo.Students和dbo.Grades)

2.實體映射到多張表

有時候我們希望一個實體的屬性分在兩種表中,那麼該怎麼配置呢?還用上邊的慄子,我們把學生的姓名和Id存在一張表,學號和Id放在另一張表中,代碼如下:

    public class SchoolContext:DbContext
    {
        public SchoolContext() : base()
        {
        }
        public DbSet<Student> Students { get; set; }
        public DbSet <Grade> Grades { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
       modelBuilder.Entity<Student>().Map(m =>
        {
          //配置第一張表,包含學生Id和學生姓名
          m.Properties(p => new { p.StudentId, p.StudentName });
          m.ToTable("StudentInfo");
        }).Map(m =>
        {
          //配置第二張表,包含學生Id和學生學號
          m.Properties(p => new { p.StudentId, p.StudentNo });
          m.ToTable("StudentInfo2");
         });

       //配置年級表名
            modelBuilder.Entity<Grade>().ToTable("GradeInfo");
        }
    }

運行一下Main函數,生成了新的資料庫,如下所示:

我們看到,通過Map()方法,我們把Student實體的屬性被分在了兩個表中。modelBuilder.Entity<T>()方法返回的是一個EntityTypeConfiguration<T>類型,Map()方法的參數是一個委托類型,委托的輸入參數是EntityMappingConfiguration的實例。我們可以自定義一個委托來實現配置,下邊的代碼運行後生成的資料庫和和上邊一樣:

    public class SchoolContext : DbContext
    {
        public SchoolContext() : base()
        {
        }
        public DbSet<Student> Students { get; set; }
        public DbSet<Grade> Grades { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //先定義一個Action委托備用,委托的輸入參數是一個實體映射配置(EntityMappingConfiguration)的實例
            Action<EntityMappingConfiguration<Student>> studentMapping = m =>
            {
                m.Properties(p => new { p.StudentId, p.StudentNo });
                m.ToTable("StudentInfo2");
            };

            modelBuilder.Entity<Student>()
                //第一張表Map()方法參數是delegate形式委托
                .Map(delegate (EntityMappingConfiguration<Student> studentConfig)
                {
                    //map參數是lambda表達式
                    studentConfig.Properties(p => new { p.StudentId, p.StudentName });
                    studentConfig.ToTable("StudentInfo");
                 })
                 //第二張表Map()方法參數是Action委托
                .Map(studentMapping);
           
            modelBuilder.Entity<Grade>().ToTable("GradeInfo");
        }
    }

 3.屬性相關配置

屬性的配置比較簡單,這裡簡單總結了主鍵,列基本屬性,是否可空,數據長度,高併發的配置。

一個慄子:

public class Student
{
    public int StudentKey { get; set; }//主鍵
    public string StudentName { get; set; }//姓名
    public DateTime DateOfBirth { get; set; }//生日
    public byte[]  Photo { get; set; }//照片
    public decimal Height { get; set; }//身高
    public float Weight { get; set; }//體重
        
    public Grade Grade{ get; set; }//年級
}
    
public class Grade
{
    public int GradeKey { get; set; }//主鍵
    public string GradeName { get; set; }//年級名
    
    public ICollection<Student> Students { get; set; }
}

 使用FluentApi對領域類做了以下配置:

 

    public class SchoolContext : DbContext
    {
        public SchoolContext() : base()
        {
        }
        public DbSet<Student> Students { get; set; }
        public DbSet<Grade> Grades { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //設置預設架構
            modelBuilder.HasDefaultSchema("Admin");
            //設置主鍵
            modelBuilder.Entity<Student>().HasKey<int>(s => s.StudentKey);
            
            //設置不映射的屬性
            modelBuilder.Entity<Student>().Ignore(s => s.Height);
            
            //設置DateOfBirth
            modelBuilder.Entity<Student>().Property(p => p.DateOfBirth)
                .HasColumnName("birthday")    //列名為birthday
                .HasColumnType("datetime2")   //數據類型是datetime類型
                .HasColumnOrder(3)            //順序編號是3
                .IsOptional();                //可以為null

            //設置姓名
            modelBuilder.Entity<Student>().Property(s => s.StudentName)
                .HasMaxLength(20)             //最長20
                .IsRequired()                 //不能為null
                .IsConcurrencyToken();        //用於樂觀併發檢測,delete或者update時,這個屬性添加到where上判斷是否併發              
        }
    }

執行程式後生成的資料庫如下:

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 文檔繼續完善整理中。。。。。。 c.DocumentFilter<SwaggerDocTag>(); /// <summary> /// Swagger註釋幫助類 /// </summary> public class SwaggerDocTag : IDocumentFilter { /// <s ...
  • 添加引用. 綁定命令. ...
  • //定義原子變數 int mituxInt = -1; //原子級別+1值,如果>=0,說明當前鎖為空,可以執行,避免重覆執行 if (Interlocked.Increment(ref mituxInt) <= 0) { if (_serverThread == null || (_serverT... ...
  • 終本案件:http://zxgk.court.gov.cn/zhongben/new_index.html 綜合執行人:http://zxgk.court.gov.cn/zhixing/new_index.html 裁判文書:http://wenshu.court.gov.cn 終本案件和執行人爬取 ...
  • 先看看為什麼要用鎖 需求:多線程處理值的加減 static int NoLockData = 0; public static void NoLockNormalTest(int threadIndex) { while (true)//這是腦殘設計,while(true) { //lock (lo ...
  • 圖表能夠很直觀的表現數據在某個時間段的變化趨勢,或者呈現數據的整體和局部之間的相互關係,相較於大篇幅的文本數據,圖表更增加了我們分析數據時選擇的多樣性,是我們挖掘數據背後潛在價值的一種更為有效地方式。在做數據彙報時,常用到PPT幻燈片來輔助工作,下麵的示例中將演示如何通過C#編程在PPT幻燈片中創建 ...
  • 首先我們知道隊列是先進先出的機制,所以在處理併發是個不錯的選擇。然後就寫兩個隊列的簡單應用。 Queue 命名空間 命名空間:System.Collections,不在這裡做過多的理論解釋,這個東西非常的好理解。 可以看下官方文檔:https://docs.microsoft.com/zh-cn/d ...
  • 1、配置代理 1、 開發機開啟 Shadowsocks,允許其他設備連入 2、 臨時開代理命令 (根據實際修改IP和埠) export http_proxy="http://10.5.21.127:1080" export https_proxy="http://10.5.21.127:1080" ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...