溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何使用Entity?Framework?Core對(duì)Web項(xiàng)目生成數(shù)據(jù)庫(kù)表

發(fā)布時(shí)間:2022-03-23 11:26:30 來源:億速云 閱讀:188 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下如何使用Entity Framework Core對(duì)Web項(xiàng)目生成數(shù)據(jù)庫(kù)表,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

一、引言

這篇文章中我們講解如何在Web項(xiàng)目中使用EntityFrameworkCore,并生成數(shù)據(jù)庫(kù)表,這里以ASP.NET Core WebApi為例講解。還是采用分層的結(jié)構(gòu)。創(chuàng)建后的項(xiàng)目整體結(jié)構(gòu)如下圖所示:

如何使用Entity?Framework?Core對(duì)Web項(xiàng)目生成數(shù)據(jù)庫(kù)表

項(xiàng)目結(jié)構(gòu):

  • EFCoreWeb.API:ASP.NET Core WebApi項(xiàng)目,用來提供Web功能,在項(xiàng)目中會(huì)引用EFCoreWeb.Data。

  • EFCoreWeb.Data:類庫(kù)項(xiàng)目,基于.NET Core的類庫(kù)。存放的是與EFCore相關(guān)的操作。

  • EFCoreWeb.Model:類庫(kù)項(xiàng)目,基于.NET Core的類庫(kù)。存放的是實(shí)體類。

1、添加實(shí)體類

我們?cè)贓FCoreWeb.Model類庫(kù)項(xiàng)目里面添加Student實(shí)體類:

namespace EFCoreWeb.Model
{
    public class Student
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

        public int Gender { get; set; }
    }
}

2、添加Mircosoft.EntityFrameworkCore

因?yàn)橐褂肧tudent實(shí)體類,首先要在EFCoreWeb.Data項(xiàng)目里面添加對(duì)EFCoreWeb.Model的引用。

然后在EFCoreWeb.Data類庫(kù)項(xiàng)目里面添加Mircosoft.EntityFrameworkCore包,直接在NuGet里面安裝:

如何使用Entity?Framework?Core對(duì)Web項(xiàng)目生成數(shù)據(jù)庫(kù)表

由于我們使用的是SQLServer數(shù)據(jù)庫(kù),所以我們還要安裝Microsoft.EntityFrameworkCore.sqlServer包,同樣也是直接在NuGet里面安裝:

如何使用Entity?Framework?Core對(duì)Web項(xiàng)目生成數(shù)據(jù)庫(kù)表

安裝完上面的兩個(gè)包以后,在EFCoreWeb.Data類庫(kù)項(xiàng)目里面添加Mapping文件夾,用來存放Fluent API的配置文件,Student類的配置伙伴類代碼如下:

using EFCoreWeb.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace EFCoreWeb.Data.Mapping
{
    /// <summary>
    /// Student配置伙伴類,繼承自IEntityTypeConfiguration<T>泛型接口
    /// </summary>
    public class StudentMap : IEntityTypeConfiguration<Student>
    {
        /// <summary>
        /// 實(shí)現(xiàn)接口里面的Configure方法,用來配置生成數(shù)據(jù)庫(kù)表結(jié)構(gòu)
        /// </summary>
        /// <param name="builder"></param>
        public void Configure(EntityTypeBuilder<Student> builder)
        {
            // 設(shè)置主鍵
            builder.HasKey(p => p.Id);
            // 設(shè)置生成的表名
            builder.ToTable("T_Student");
            // 設(shè)置Name列的最大長(zhǎng)度
            builder.Property("Name").HasMaxLength(64);
            // 設(shè)置Name列是必須的
            builder.Property("Name").IsRequired();
        }
    }
}

添加一個(gè)Context文件夾,然后添加數(shù)據(jù)上下文類,繼承自DbContext:

using EFCoreWeb.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace EFCoreWeb.Data.Mapping
{
    /// <summary>
    /// Student配置伙伴類,繼承自IEntityTypeConfiguration<T>泛型接口
    /// </summary>
    public class StudentMap : IEntityTypeConfiguration<Student>
    {
        /// <summary>
        /// 實(shí)現(xiàn)接口里面的Configure方法,用來配置生成數(shù)據(jù)庫(kù)表結(jié)構(gòu)
        /// </summary>
        /// <param name="builder"></param>
        public void Configure(EntityTypeBuilder<Student> builder)
        {
            // 設(shè)置主鍵
            builder.HasKey(p => p.Id);
            // 設(shè)置生成的表名
            builder.ToTable("T_Student");
            // 設(shè)置Name列的最大長(zhǎng)度
            builder.Property("Name").HasMaxLength(64);
            // 設(shè)置Name列是必須的
            builder.Property("Name").IsRequired();
        }
    }
}

二、生成數(shù)據(jù)庫(kù)表

這里我們使用程序包管理器控制臺(tái)遷移的方式來生成數(shù)據(jù)庫(kù)表。需要在EFCoreWeb.Data項(xiàng)目里面安裝Microsoft.EntityFrameworkCore.Tools包。在EFCoreWeb.API項(xiàng)目里面安裝Microsoft.EntityFrameworkCore.Tools、Microsoft.EntityFrameworkCore兩個(gè)包。EFCoreWeb.API項(xiàng)目添加對(duì)EFCoreWeb.Data項(xiàng)目的引用。

首先在EFCoreWeb.API項(xiàng)目的appsettings.json文件里面添加數(shù)據(jù)庫(kù)連接字符串:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionString": {
    "DbConnection": "Data Source=.;Initial Catalog=EFTestDb;User ID=sa;Password=123456;"
  }
}

在Startup類的ConfigureServices方法里面添加數(shù)據(jù)庫(kù)連接:

using EFCoreWeb.Data.Context;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace EFCoreWeb.API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region 數(shù)據(jù)庫(kù)連接
            services.AddDbContext<EFCoreDbContext>(options => {
                // options.UseSqlServer(Configuration.GetConnectionString("DbConnection"));
                options.UseSqlServer(Configuration.GetSection("ConnectionString").GetSection("DbConnection").Value);
            });
            #endregion
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

上面步驟配置完成以后,在程序包管理器控制臺(tái)里面開始遷移,使用下面的命令添加遷移:

Add-Migration Init

如下圖所示:

如何使用Entity?Framework?Core對(duì)Web項(xiàng)目生成數(shù)據(jù)庫(kù)表

執(zhí)行完命令以后就會(huì)生成遷移文件:

如何使用Entity?Framework?Core對(duì)Web項(xiàng)目生成數(shù)據(jù)庫(kù)表

添加遷移之后,執(zhí)行下面的命令更新數(shù)據(jù)庫(kù):

Update-Database

如下圖所示:

如何使用Entity?Framework?Core對(duì)Web項(xiàng)目生成數(shù)據(jù)庫(kù)表

執(zhí)行完以后去查看數(shù)據(jù)庫(kù):

如何使用Entity?Framework?Core對(duì)Web項(xiàng)目生成數(shù)據(jù)庫(kù)表

可以看到,表里面Name列的長(zhǎng)度是根據(jù)代碼里面設(shè)置的長(zhǎng)度生成的,而且不為null,種子數(shù)據(jù)也插入進(jìn)去了。

看完了這篇文章,相信你對(duì)“如何使用Entity Framework Core對(duì)Web項(xiàng)目生成數(shù)據(jù)庫(kù)表”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI