EF Core Code First 是什么
Code First 是 Entity Framework Core (簡(jiǎn)稱 EF Core) 的一種開(kāi)發(fā)模式,它允許開(kāi)發(fā)人員使用純粹的代碼來(lái)定義數(shù)據(jù)模型,通過(guò)它,可以極大地提高開(kāi)發(fā)效率:
- 使用 Code First 開(kāi)發(fā)模式,你可以專注于定義領(lǐng)域模型和業(yè)務(wù)邏輯,而無(wú)需關(guān)注數(shù)據(jù)庫(kù)的細(xì)節(jié),能夠更快地構(gòu)建應(yīng)用程序
- Code First 是真正地面向?qū)ο蟮姆绞絹?lái)定義數(shù)據(jù)模型,包括實(shí)體類、關(guān)系、繼承等,這些都讓數(shù)據(jù)模型的設(shè)計(jì)更加直觀和易于理解
- Code First 支持多種數(shù)據(jù)庫(kù),包括 SQL Server、MySQL、PostgreSQL 等,你可以在不同的數(shù)據(jù)庫(kù)之間進(jìn)行切換而無(wú)需修改代碼
- Code First 提供了數(shù)據(jù)庫(kù)遷移工具,可以根據(jù)模型變化自動(dòng)創(chuàng)建、更新和維護(hù)數(shù)據(jù)庫(kù)模式,數(shù)據(jù)庫(kù)的版本控制和遷移變得更加容易,也減少了手動(dòng)編寫 SQL 腳本的工作量
Step By Step 使用 Code First 步驟
- 創(chuàng)建一個(gè) asp.net core Console 項(xiàng)目
- 從 Nuget 安裝以下包
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools - 創(chuàng)建實(shí)體類 Article 和 Comment
public class Article { /// <summary> /// 主鍵 /// </summary> public long Id { get; set; } /// <summary> /// 標(biāo)題 /// </summary> public string Title { get; set; } /// <summary> /// 內(nèi)容 /// </summary> public string Content { get; set; } /// <summary> /// 此文章的若干條評(píng)論 /// </summary> public List<Comment> Comments { get; set; } = new List<Comment>(); } public class Comment { public long Id { get; set; } public Article Article { get; set; } public long ArticleId { get; set; } public string Message { get; set; } }
- 創(chuàng)建實(shí)現(xiàn)了IEntityTypeConfiguration接口的實(shí)體類的配置類,用于配置實(shí)體類和數(shù)據(jù)庫(kù)表的對(duì)應(yīng)關(guān)系
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; // IEntityTypeConfiguration的泛型參數(shù)類指定這個(gè)類要對(duì)實(shí)體類 Article 進(jìn)行配置 class ArticleConfig : IEntityTypeConfiguration<Article> { // 使用Fluent API的方式對(duì)實(shí)體類進(jìn)行配置 // 也可以在實(shí)體類中使用 Data Annotation 進(jìn)行配置,但那樣耦合太深,不推薦使用 public void Configure(EntityTypeBuilder<Article> builder) { // 表示這個(gè)實(shí)體類對(duì)應(yīng)數(shù)據(jù)庫(kù)中名字為T_Articles的表 builder.ToTable("T_Articles"); builder.Property(p => p.Content).IsRequired().IsUnicode(); builder.Property(p => p.Title).IsRequired().IsUnicode() .HasMaxLength(255); } } class CommentConfig : IEntityTypeConfiguration<Comment> { public void Configure(EntityTypeBuilder<Comment> builder) { builder.ToTable("T_Comments"); // 一條評(píng)論對(duì)應(yīng)一篇文章,一篇文章有多條評(píng)論 builder.HasOne<Article>(c =>c.Article) .WithMany(a => a.Comments) .IsRequired() .HasForeignKey(c => c.ArticleId); builder.Property(p=>p.Message).IsRequired().IsUnicode(); } }
- 創(chuàng)建一個(gè)繼承自DbContext類的TestDbContext類(上下文類)
using Microsoft.EntityFrameworkCore; class TestDbContext: DbContext { public DbSet<Article> Articles { get; set; } public DbSet<Comment> Comments { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { string connStr = "Server=(localdb)\\mssqllocaldb;Database=TestDB;Trusted_Connection=True;MultipleActiveResultSets=true"; optionsBuilder.UseSqlServer(connStr); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // 表示加載當(dāng)前程序集中所有實(shí)現(xiàn)了IEntityTypeConfiguration接口的類 modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly); } }
- 遷移(根據(jù)實(shí)體類生成數(shù)據(jù)庫(kù)表)
- 打開(kāi) 菜單 - 工具 - 程序包管理器控制臺(tái)
- 默認(rèn)項(xiàng)目下拉框選擇目標(biāo)項(xiàng)目【可選,如果解決方案有多個(gè)項(xiàng)目】
- 執(zhí)行如下命令:
Add-Migration InitialCreate 【InitialCreate 名字可隨意取,有意義就好】
說(shuō)明:Add-Migration命令會(huì)自動(dòng)在項(xiàng)目的Migrations文件夾中生成C#代碼文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-760683.html - 執(zhí)行命令
Update-database
說(shuō)明:編譯并且執(zhí)行數(shù)據(jù)庫(kù)遷移代碼文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-760683.html - 查看 sql server 數(shù)據(jù)庫(kù)是否執(zhí)行成功
- 如果添加或修改字段,重復(fù)執(zhí)行3~4步命令
- 至此,EF Core 的 Code First 過(guò)程已經(jīng)完成,接著就可以對(duì)數(shù)據(jù)進(jìn)行增刪改查等操作
擴(kuò)展 - Fluent API 基本語(yǔ)法例子
- 視圖與實(shí)體類映射
modelBuilder.Entity<Blog>().ToView("blogsView");
- 排除屬性映射
modelBuilder.Entity<Blog>().Ignore(b => b. Name2);
- 數(shù)據(jù)庫(kù)表列名
modelBuilder.Entity<Blog>().Property(b =>b.BlogId).HasColumnName("blog_id");
- 列數(shù)據(jù)類型
builder.Property(e => e.Title) .HasColumnType("varchar(200)")
- 主鍵
modelBuilder.Entity<Student>().HasKey(c => c.Number);
- 索引
modelBuilder.Entity<Blog>().HasIndex(b => b.Url); // 復(fù)合索引 modelBuilder.Entity<Person>().HasIndex(p => new { p.FirstName, p.LastName });
- 多對(duì)多
builder.HasMany<Teacher>(c => c.Teachers).WithMany(t => t.Students) .UsingEntity(j => j.ToTable("T_Students_Teachers"));
- 1對(duì)多
builder.HasOne<Article>(c =>c.Article) .WithMany(a => a.Comments) .IsRequired() .HasForeignKey(c => c.ArticleId);
- 1對(duì)1
builder.HasOne<Delivery>(c => c.Delivery).WithOne(d => d.Order) .HasForeignKey<Delivery>(d => d.OrderId);
到了這里,關(guān)于不會(huì)使用 EF Core 的 Code First 模式?來(lái)看看這篇文章,手把手地教你的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!