EntityFrameworkCore教程:Web項目生成數據庫表

一、引言

這篇文章中我們講解如何在Web項目中使用EntityFrameworkCore,並生成數據庫表,這裏以ASP.NET Core WebApi爲例講解。還是採用分層的結構。創建後的項目整體結構如下圖所示:

項目結構:

  1. EFCoreWeb.API:ASP.NET Core WebApi項目,用來提供Web功能,在項目中會引用EFCoreWeb.Data。
  2. EFCoreWeb.Data:類庫項目,基於.NET Core的類庫。存放的是與EFCore相關的操作。
  3. EFCoreWeb.Model:類庫項目,基於.NET Core的類庫。存放的是實體類。

1、添加實體類

我們在EFCoreWeb.Model類庫項目裏面添加Student實體類:

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

因爲要使用Student實體類,首先要在EFCoreWeb.Data項目裏面添加對EFCoreWeb.Model的引用。

然後在EFCoreWeb.Data類庫項目裏面添加Mircosoft.EntityFrameworkCore包,直接在NuGet裏面安裝:

由於我們使用的是SQLServer數據庫,所以我們還要安裝Microsoft.EntityFrameworkCore.sqlServer包,同樣也是直接在NuGet裏面安裝:

 安裝完上面的兩個包以後,在EFCoreWeb.Data類庫項目裏面添加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>
        /// 實現接口裏面的Configure方法,用來配置生成數據庫表結構
        /// </summary>
        /// <param name="builder"></param>
        public void Configure(EntityTypeBuilder<Student> builder)
        {
            // 設置主鍵
            builder.HasKey(p => p.Id);
            // 設置生成的表名
            builder.ToTable("T_Student");
            // 設置Name列的最大長度
            builder.Property("Name").HasMaxLength(64);
            // 設置Name列是必須的
            builder.Property("Name").IsRequired();
        }
    }
}

添加一個Context文件夾,然後添加數據上下文類,繼承自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>
        /// 實現接口裏面的Configure方法,用來配置生成數據庫表結構
        /// </summary>
        /// <param name="builder"></param>
        public void Configure(EntityTypeBuilder<Student> builder)
        {
            // 設置主鍵
            builder.HasKey(p => p.Id);
            // 設置生成的表名
            builder.ToTable("T_Student");
            // 設置Name列的最大長度
            builder.Property("Name").HasMaxLength(64);
            // 設置Name列是必須的
            builder.Property("Name").IsRequired();
        }
    }
}

二、生成數據庫表

這裏我們使用程序包管理器控制檯遷移的方式來生成數據庫表。需要在EFCoreWeb.Data項目裏面安裝Microsoft.EntityFrameworkCore.Tools包。在EFCoreWeb.API項目裏面安裝Microsoft.EntityFrameworkCore.Tools、Microsoft.EntityFrameworkCore兩個包。EFCoreWeb.API項目添加對EFCoreWeb.Data項目的引用。

首先在EFCoreWeb.API項目的appsettings.json文件裏面添加數據庫連接字符串:

{
  "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方法裏面添加數據庫連接:

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 數據庫連接
            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();
            });
        }
    }
}

上面步驟配置完成以後,在程序包管理器控制檯裏面開始遷移,使用下面的命令添加遷移:

Add-Migration Init

如下圖所示:

執行完命令以後就會生成遷移文件:

添加遷移之後,執行下面的命令更新數據庫:

Update-Database

如下圖所示:

執行完以後去查看數據庫:

可以看到,表裏面Name列的長度是根據代碼裏面設置的長度生成的,而且不爲null,種子數據也插入進去了。 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章