欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2022年03月23日 09:23:14   作者:.NET開(kāi)發(fā)菜鳥(niǎo)  
這篇文章介紹了Entity Framework Core對(duì)Web項(xiàng)目生成數(shù)據(jù)庫(kù)表的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

一、引言

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

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

  • EFCoreWeb.API:ASP.NET Core WebApi項(xiàng)目,用來(lái)提供Web功能,在項(xiàng)目中會(huì)引用EFCoreWeb.Data。
  • EFCoreWeb.Data:類(lèi)庫(kù)項(xiàng)目,基于.NET Core的類(lèi)庫(kù)。存放的是與EFCore相關(guān)的操作。
  • EFCoreWeb.Model:類(lèi)庫(kù)項(xiàng)目,基于.NET Core的類(lèi)庫(kù)。存放的是實(shí)體類(lèi)。

1、添加實(shí)體類(lèi)

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

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í)體類(lèi),首先要在EFCoreWeb.Data項(xiàng)目里面添加對(duì)EFCoreWeb.Model的引用。

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

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

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

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

namespace EFCoreWeb.Data.Mapping
{
    /// <summary>
    /// Student配置伙伴類(lèi),繼承自IEntityTypeConfiguration<T>泛型接口
    /// </summary>
    public class StudentMap : IEntityTypeConfiguration<Student>
    {
        /// <summary>
        /// 實(shí)現(xiàn)接口里面的Configure方法,用來(lái)配置生成數(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ù)上下文類(lèi),繼承自DbContext:

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

namespace EFCoreWeb.Data.Mapping
{
    /// <summary>
    /// Student配置伙伴類(lèi),繼承自IEntityTypeConfiguration<T>泛型接口
    /// </summary>
    public class StudentMap : IEntityTypeConfiguration<Student>
    {
        /// <summary>
        /// 實(shí)現(xiàn)接口里面的Configure方法,用來(lái)配置生成數(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)遷移的方式來(lá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類(lèi)的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)里面開(kāi)始遷移,使用下面的命令添加遷移:

Add-Migration Init

如下圖所示:

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

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

Update-Database

如下圖所示:

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

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

到此這篇關(guān)于Entity Framework Core對(duì)Web項(xiàng)目生成數(shù)據(jù)庫(kù)表的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論