網站首頁 編程語言 正文
一、引言
這篇文章中我們講解如何在Web項目中使用EntityFrameworkCore,并生成數據庫表,這里以ASP.NET Core WebApi為例講解。還是采用分層的結構。創建后的項目整體結構如下圖所示:
項目結構:
- EFCoreWeb.API:ASP.NET Core WebApi項目,用來提供Web功能,在項目中會引用EFCoreWeb.Data。
- EFCoreWeb.Data:類庫項目,基于.NET Core的類庫。存放的是與EFCore相關的操作。
- 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 { ////// Student配置伙伴類,繼承自IEntityTypeConfiguration public class StudentMap : IEntityTypeConfiguration泛型接口 /// { /// /// 實現接口里面的Configure方法,用來配置生成數據庫表結構 /// /// public void Configure(EntityTypeBuilderbuilder) { // 設置主鍵 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 { ////// Student配置伙伴類,繼承自IEntityTypeConfiguration public class StudentMap : IEntityTypeConfiguration泛型接口 /// { /// /// 實現接口里面的Configure方法,用來配置生成數據庫表結構 /// /// public void Configure(EntityTypeBuilderbuilder) { // 設置主鍵 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(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,種子數據也插入進去了。
原文鏈接:https://www.cnblogs.com/dotnet261010/p/12354850.html
相關推薦
- 2022-11-09 docker容器直接退出如何進入容器調試模式_docker
- 2022-04-17 C語言中用棧+隊列實現隊列中的元素逆置_C 語言
- 2022-04-21 C語言中結構體實例解析_C 語言
- 2022-06-21 Android?使用flow實現倒計時的方式_Android
- 2022-12-21 Input系統之InputReader處理按鍵事件詳解_Android
- 2022-07-30 Linux的磁盤配額設置
- 2022-04-04 iview在Table表格中渲染title文字提示,使用render實現
- 2022-04-14 Python中字典的相關操作介紹_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支