自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

深入探索 EF Core 數(shù)據(jù)庫遷移與表生成實體

開發(fā) 前端
在實際項目中,可根據(jù)團隊開發(fā)流程靈活運用,如在新項目啟動時利用遷移創(chuàng)建初始架構(gòu),后期迭代持續(xù)更新;對接遺留數(shù)據(jù)庫時,先逆向生成實體再按需優(yōu)化調(diào)整,充分發(fā)揮 EF Core 的強大功能。

一、引言

Entity Framework Core(EF Core)作為一款強大的對象關(guān)系映射(ORM)框架,在.NET 開發(fā)中廣泛應(yīng)用于數(shù)據(jù)庫交互。其中,數(shù)據(jù)庫遷移功能允許我們以代碼優(yōu)先的方式管理數(shù)據(jù)庫架構(gòu)的演變,而從現(xiàn)有數(shù)據(jù)庫表生成實體類則為逆向工程提供了便利,大大提高開發(fā)效率。本文將詳細講解這兩個關(guān)鍵操作的具體步驟,并附上實例,幫助讀者快速上手。

二、EF Core 數(shù)據(jù)庫遷移

(一)環(huán)境搭建

首先,確保你的項目已安裝必要的 NuGet 包。對于一個.NET Core 項目,需要引入  Microsoft.EntityFrameworkCore 、 Microsoft.EntityFrameworkCore.Design 、 Microsoft.EntityFrameworkCore.SqlServer (這里以 SQL Server 為例,若使用其他數(shù)據(jù)庫,如 MySQL,則引入對應(yīng)的包,如  Pomelo.EntityFrameworkCore.MySql )。

(二)創(chuàng)建 DbContext 類

DbContext 是 EF Core 與數(shù)據(jù)庫交互的核心類,它負責協(xié)調(diào)實體類與數(shù)據(jù)庫之間的操作。例如,創(chuàng)建一個名為  MyDbContext  的類:

復制

using Microsoft.EntityFrameworkCore;

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
    }

    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

這里定義了兩個  DbSet  屬性,分別對應(yīng)  Blog  和  Post  實體(后續(xù)會詳細講解實體類),它們代表數(shù)據(jù)庫中的表。

(三)配置數(shù)據(jù)庫連接

在  Startup.cs (ASP.NET Core 項目)或程序入口點處,配置數(shù)據(jù)庫連接字符串并將  DbContext  注入到服務(wù)容器中:

復制

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        var connectionString = "Server=(localdb)\\mssqllocaldb;Database=MyBlogDb;Trusted_Connection=True;";
        services.AddDbContext<MyDbContext>(options =>
            options.UseSqlServer(connectionString));

        // 其他服務(wù)注冊
    }

    // 其他配置方法
}

(四)創(chuàng)建初始遷移

打開命令行工具,切換到項目目錄,執(zhí)行以下命令:

復制

dotnet ef migrations add InitialCreate

這一步會在項目中創(chuàng)建一個  Migrations  文件夾,里面包含了描述數(shù)據(jù)庫初始架構(gòu)的代碼文件。例如,生成的遷移文件可能包含創(chuàng)建  Blogs  和  Posts  表的代碼,類似:

復制

public partial class InitialCreate : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "Blogs",
            columns: table => new
            {
                BlogId = table.Column<int>(nullable: false)
                   .Annotation("SqlServer:Identity", "1, 1"),
                Url = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Blogs", x => x.BlogId);
            });

        migrationBuilder.CreateTable(
            name: "Posts",
            columns: table => new
            {
                PostId = table.Column<int>(nullable: false)
                   .Annotation("SqlServer:Identity", "1, 1"),
                Title = table.Column<string>(nullable: true),
                Content = table.Column<string>(nullable: true),
                BlogId = table.Column<int>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Posts", x => x.PostId);
                table.ForeignKey(
                    name: "FK_Posts_Blogs_BlogId",
                    column: x => x.BlogId,
                    principalTable: "Blogs",
                    principalColumn: "BlogId",
                    onDelete: ReferentialAction.Cascade);
            });
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: "Posts");
        migrationBuilder.DropTable(
            name: "Blogs");
    }
}

 Up  方法定義了如何將數(shù)據(jù)庫遷移到新版本,即創(chuàng)建表; Down  方法則用于回滾遷移,刪除相應(yīng)表。

(五)應(yīng)用遷移到數(shù)據(jù)庫

執(zhí)行以下命令將遷移應(yīng)用到數(shù)據(jù)庫:

復制

dotnet ef database update

此時,數(shù)據(jù)庫中會創(chuàng)建  Blogs  和  Posts  表,架構(gòu)與遷移文件中定義一致。

三、從數(shù)據(jù)庫表生成實體

(一)安裝反向工程工具

EF Core 提供了反向工程工具,同樣需要通過 NuGet 安裝。執(zhí)行命令:

復制

dotnet tool install --global dotnet-ef

確保工具安裝成功。

(二)生成實體類

在命令行中,執(zhí)行以下命令:

復制

dotnet ef dbcontext scaffold "Server=(localdb)\\mssqllocaldb;Database=MyBlogDb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models

這里的連接字符串指向要逆向工程的數(shù)據(jù)庫, Microsoft.EntityFrameworkCore.SqlServer  表明數(shù)據(jù)庫類型, -o Models  指定生成的實體類文件輸出到  Models  文件夾。

生成的實體類會自動包含對應(yīng)表的屬性,例如  Blog  實體可能如下:

復制

public partial class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public ICollection<Post> Posts { get; set; }
}
 
 
 Post  實體也會有相應(yīng)屬性,并且會自動配置與  Blog  的關(guān)聯(lián)關(guān)系,類似:
 
public partial class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public int BlogId { get; set; }
    public virtual Blog Blog { get; set; }
}

四、總結(jié)

通過 EF Core 的數(shù)據(jù)庫遷移功能,我們能以優(yōu)雅的代碼方式管理數(shù)據(jù)庫架構(gòu)變化,適應(yīng)項目迭代需求。而從數(shù)據(jù)庫表生成實體的逆向工程操作,則為對接已有數(shù)據(jù)庫、快速構(gòu)建數(shù)據(jù)訪問層提供了高效途徑。掌握這兩項技術(shù),能讓.NET 開發(fā)者在數(shù)據(jù)庫驅(qū)動的應(yīng)用開發(fā)中如虎添翼,提升開發(fā)效率與代碼質(zhì)量,輕松應(yīng)對復雜的數(shù)據(jù)持久化場景。

在實際項目中,可根據(jù)團隊開發(fā)流程靈活運用,如在新項目啟動時利用遷移創(chuàng)建初始架構(gòu),后期迭代持續(xù)更新;對接遺留數(shù)據(jù)庫時,先逆向生成實體再按需優(yōu)化調(diào)整,充分發(fā)揮 EF Core 的強大功能。

責任編輯:武曉燕 來源: 程序員編程日記
相關(guān)推薦

2013-09-08 22:12:02

EF Code Fir數(shù)據(jù)遷移MVC架構(gòu)設(shè)計

2016-08-23 13:35:22

MVCEFNuGet

2012-09-10 10:23:38

Entity Fram

2025-01-10 00:32:48

2017-06-12 18:24:25

數(shù)據(jù)庫壓縮技術(shù)

2021-03-17 00:05:50

分布式事務(wù)提交

2025-02-10 09:10:32

2011-09-23 09:09:38

數(shù)據(jù)庫遷移

2020-08-13 07:42:15

數(shù)據(jù)庫Flyway代碼

2010-08-04 16:18:48

DB2數(shù)據(jù)庫

2024-11-25 06:30:00

2025-01-22 08:19:34

2022-04-19 09:53:06

云數(shù)據(jù)庫云計算數(shù)據(jù)庫

2018-06-21 10:05:07

數(shù)據(jù)庫管理SQL解析MySQL

2022-06-30 10:56:18

字節(jié)云數(shù)據(jù)庫存儲

2024-06-06 16:50:15

2023-02-01 13:22:00

數(shù)據(jù)庫表連接SQL

2009-07-16 09:48:29

數(shù)據(jù)庫連接

2009-03-19 09:44:07

SQL Server數(shù)據(jù)庫遷移數(shù)據(jù)庫

2011-04-29 14:30:23

點贊
收藏

51CTO技術(shù)棧公眾號