網(wǎng)站首頁 編程語言 正文
一、引言
這篇文章中我們講解如何在Web項(xiàng)目中使用EntityFrameworkCore,并生成數(shù)據(jù)庫表,這里以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)目,用來提供Web功能,在項(xiàng)目中會引用EFCoreWeb.Data。
- EFCoreWeb.Data:類庫項(xiàng)目,基于.NET Core的類庫。存放的是與EFCore相關(guān)的操作。
- EFCoreWeb.Model:類庫項(xiàng)目,基于.NET Core的類庫。存放的是實(shí)體類。
1、添加實(shí)體類
我們在EFCoreWeb.Model類庫項(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)目里面添加對EFCoreWeb.Model的引用。
然后在EFCoreWeb.Data類庫項(xiàng)目里面添加Mircosoft.EntityFrameworkCore包,直接在NuGet里面安裝:
由于我們使用的是SQLServer數(shù)據(jù)庫,所以我們還要安裝Microsoft.EntityFrameworkCore.sqlServer包,同樣也是直接在NuGet里面安裝:
安裝完上面的兩個包以后,在EFCoreWeb.Data類庫項(xiàng)目里面添加Mapping文件夾,用來存放Fluent API的配置文件,Student類的配置伙伴類代碼如下:
using EFCoreWeb.Model; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace EFCoreWeb.Data.Mapping { ////// Student配置伙伴類,繼承自IEntityTypeConfiguration public class StudentMap : IEntityTypeConfiguration泛型接口 /// { /// /// 實(shí)現(xiàn)接口里面的Configure方法,用來配置生成數(shù)據(jù)庫表結(jié)構(gòu) /// /// public void Configure(EntityTypeBuilderbuilder) { // 設(shè)置主鍵 builder.HasKey(p => p.Id); // 設(shè)置生成的表名 builder.ToTable("T_Student"); // 設(shè)置Name列的最大長度 builder.Property("Name").HasMaxLength(64); // 設(shè)置Name列是必須的 builder.Property("Name").IsRequired(); } } }
添加一個Context文件夾,然后添加數(shù)據(jù)上下文類,繼承自DbContext:
using EFCoreWeb.Model; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace EFCoreWeb.Data.Mapping { ////// Student配置伙伴類,繼承自IEntityTypeConfiguration public class StudentMap : IEntityTypeConfiguration泛型接口 /// { /// /// 實(shí)現(xiàn)接口里面的Configure方法,用來配置生成數(shù)據(jù)庫表結(jié)構(gòu) /// /// public void Configure(EntityTypeBuilderbuilder) { // 設(shè)置主鍵 builder.HasKey(p => p.Id); // 設(shè)置生成的表名 builder.ToTable("T_Student"); // 設(shè)置Name列的最大長度 builder.Property("Name").HasMaxLength(64); // 設(shè)置Name列是必須的 builder.Property("Name").IsRequired(); } } }
二、生成數(shù)據(jù)庫表
這里我們使用程序包管理器控制臺遷移的方式來生成數(shù)據(jù)庫表。需要在EFCoreWeb.Data項(xiàng)目里面安裝Microsoft.EntityFrameworkCore.Tools包。在EFCoreWeb.API項(xiàng)目里面安裝Microsoft.EntityFrameworkCore.Tools、Microsoft.EntityFrameworkCore兩個包。EFCoreWeb.API項(xiàng)目添加對EFCoreWeb.Data項(xiàng)目的引用。
首先在EFCoreWeb.API項(xiàng)目的appsettings.json文件里面添加數(shù)據(jù)庫連接字符串:
{ "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ù)庫連接:
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ù)庫連接 services.AddDbContext(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
如下圖所示:
執(zhí)行完命令以后就會生成遷移文件:
添加遷移之后,執(zhí)行下面的命令更新數(shù)據(jù)庫:
Update-Database
如下圖所示:
執(zhí)行完以后去查看數(shù)據(jù)庫:
可以看到,表里面Name列的長度是根據(jù)代碼里面設(shè)置的長度生成的,而且不為null,種子數(shù)據(jù)也插入進(jìn)去了。
原文鏈接:https://www.cnblogs.com/dotnet261010/p/12354850.html
相關(guān)推薦
- 2022-08-04 Python?編程操作連載之字符串,列表,字典和集合處理_python
- 2022-06-20 深入淺析C#?11?對?ref?和?struct?的改進(jìn)_C#教程
- 2022-05-24 C#多線程TPL模式下使用HttpClient_C#教程
- 2022-10-23 Kubernetes?k8s?configmap?容器技術(shù)解析_云其它
- 2022-08-05 Activity supporting ACTION_VIEW is not exported
- 2022-10-02 C#使用is、as關(guān)鍵字以及顯式強(qiáng)轉(zhuǎn)實(shí)現(xiàn)引用類型轉(zhuǎn)換_C#教程
- 2022-04-09 Mybatis-Plus中dao層、service封裝的方法
- 2022-04-14 android studio不顯示當(dāng)前手機(jī)app進(jìn)程
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支