当前位置:网站首页>5. Data access - entityframework integration
5. Data access - entityframework integration
2022-07-07 05:33:00 【MASA team】
Preface
Masa Provides the basis for EntityFramework Data integration for , It also provides the functions of data filtering and soft deletion , Now we will introduce how to use it ?
MasaDbContext introduction
- install .Net 6.0
newly build ASP.NET Core Empty item
Assignment.MasaEntityFramework, And installMasa.Contrib.Data.EntityFrameworkCore、Swashbuckle.AspNetCore、Microsoft.EntityFrameworkCore.InMemory、Microsoft.EntityFrameworkCore.Toolsdotnet add package Masa.Contrib.Data.EntityFrameworkCore --version 0.4.0-rc.4 dotnet add package Swashbuckle.AspNetCore --version 6.2.3 dotnet add package Microsoft.EntityFrameworkCore.InMemory --version 6.0.5 dotnet add package Microsoft.EntityFrameworkCore.Tools --version 6.0.5install
Swashbuckle.AspNetCoreFor the convenience of passingSwaggerTo operate the service
installMicrosoft.EntityFrameworkCore.InMemoryIt's for convenience , So use an in memory database , If you need to use other databases , Please install the corresponding package by yourself
installMicrosoft.EntityFrameworkCore.ToolsTo use CodeFirst Create databaseThe new class
Userpublic class User { public int Id { get; set; } public string Name { get; set; } public uint Gender { get; set; } public DateTime BirthDay { get; set; } public DateTime CreationTime { get; set; } public User() { this.CreationTime = DateTime.Now; } }New user context
UserDbContext.cspublic class UserDbContext : MasaDbContext { public DbSet<User> User { get; set; } public UserDbContext(MasaDbContextOptions options) : base(options) { } }UserDbContextInstead of inheritanceMasaDbContext, And add a parameter constructor , Parameter type isMasaDbContextOptions
When there are multiple DbContext when , It needs to be inheritedMasaDbContext<TDbContext>, The constructor parameter type is changed toMasaDbContext<TDbContext>The new class
AddUserRequestAs a parameter for adding userspublic class AddUserRequest { public string Name { get; set; } public uint Gender { get; set; } public DateTime BirthDay { get; set; } }The new class
HostExtensionsFor migrating databases ( Use CodeFirst)public static class HostExtensions { public static void MigrateDbContext<TContext>( this IHost host, Action<TContext, IServiceProvider> seeder) where TContext : DbContext { using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetRequiredService<TContext>(); context.Database.EnsureCreated(); seeder(context, services); } } }modify
Program.cs, newly addedSwaggerSupportbuilder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); app.UseSwagger(); app.UseSwaggerUI();
Unwanted
SwaggerDon't add , Use Swagger Just to test and invoke the service , UsePostmanOr something else Http Tools can also
modify
Program.cs, Add user context ( a key )builder.Services.AddMasaDbContext<UserDbContext>(options => { options.Builder = (_, dbContextOptionsBuilder) => dbContextOptionsBuilder.UseInMemoryDatabase("test") });modify
Program.cs, Make the project support CodeFirstapp.MigrateDbContext<UserDbContext>((context, services) => { });Unwanted CodeFirst, Code generation is not supported, and the database cannot be added
test
MasaDbContext, modifyProgram.csapp.MapPost("/add", (UserDbContext dbContext, [FromBody] AddUserRequest request) => { dbContext.Set<User>().Add(new User() { Name = request.Name, Gender = request.Gender, BirthDay = request.BirthDay }); dbContext.SaveChanges(); }); app.MapGet("/list", (UserDbContext dbContext) => { return dbContext.Set<User>().ToList(); });Run the project by yourself , perform
addThen create a new user , After performinglistGet more than one user data , Then proveMasaDbContextCorrect use
How to use soft delete
Choose
Assignment.MasaEntityFrameworkAnd installMasa.Contrib.Data.Contracts.EFdotnet add package Masa.Contrib.Data.Contracts.EF --version 0.4.0-rc.4Modify the class
User, And implementISoftDelete, Change the code to :public class User : ISoftDelete// a key : Change to implementation ISoftDelete { public int Id { get; set; } public string Name { get; set; } public uint Gender { get; set; } public DateTime BirthDay { get; set; } public DateTime CreationTime { get; set; } public bool IsDeleted { get; private set; } public User() { this.CreationTime = DateTime.Now; } }Increase implementation
ISoftDelete, And forIsDeletedAttribute addition set Support ( It can be private set;)modify
Program.cs, And enable data filteringbuilder.Services.AddMasaDbContext<UserDbContext>(options => { options.Builder = (_, dbContextOptionsBuilder) => dbContextOptionsBuilder.UseInMemoryDatabase("test"); options.UseFilter();// Enable data filtering , Complete writing :options.UseFilter(filterOptions => filterOptions.EnableSoftDelete = true); });Test whether the soft deletion is successful
modify
Program.cs, Add delete methodapp.MapDelete("/delete", (UserDbContext dbContext, int id) => { var user = dbContext.Set<User>().First(u => u.Id == id); dbContext.Set<User>().Remove(user); dbContext.SaveChanges(); });
Last , First call add Method after creating the user , Call later list Method to get the list of all users , And take out any one id Information , Then call delete Method to delete the user , Last call list Method , View removed id Whether there is , To verify whether the soft deletion is effective .
How to temporarily disable soft deletion filtering
In the default query, the data marked with deleted tags will be filtered and no longer be queried , But there are also some scenarios that need to query all the data , At this point, you need to use data filtering IDataFilter
newly added
AllMethod is used to query all data ( Contains data marked as deleted )app.MapGet("/all", (UserDbContext dbContext, [FromServices] IDataFilter dataFilter) => { // adopt DI Get IDataFilter, And call it Disable Method can be temporarily disabled ISoftDelete filter using (dataFilter.Disable<ISoftDelete>()) { return dbContext.Set<User>().ToList(); } });Rerun the project , Repeat the steps of verifying soft deletion , Make sure to pass
listMethod cannot access dataThe reason for repeating the verify soft delete step is that this example uses an in memory database , After the project stops , All data will be cleared , Re execution is to ensure that the data exists , Only marked for deletion
perform
allMethod , Get all the data , see id Whether the corresponding user data exists
Get the database connection string from the configuration file
Selected items
Assignment.MasaEntityFramework, And installMasa.Contrib.Data.EntityFrameworkCore.InMemorydotnet add package Masa.Contrib.Data.EntityFrameworkCore.InMemory --version 0.4.0-rc.4Install the corresponding database package as needed , Such as :
Masa.Contrib.Data.EntityFrameworkCore.SqlServer(SqlServer)、Masa.Contrib.Data.EntityFrameworkCore.Pomelo.MySql(Pomelo Provided MySql)、Masa.Contrib.Data.EntityFrameworkCore.Oracle(Oracle) etc.modify
Program.cs, Adjust the configuration of adding user context to :builder.Services.AddMasaDbContext<UserDbContext>(options => options.UseInMemoryDatabase().UseFilter());modify
appsettings.json, Add user database connection string :{ "ConnectionStrings": { "DefaultConnection": "test"// Replace with the specified database connection string } }modify
Program.cs, newly addeddatabaseMethod , Verify that the current database istestapp.MapGet("/database", (UserDbContext dbContext) => { var field = typeof(MasaDbContext).GetField("Options", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic)!; var masaDbContextOptions = field.GetValue(dbContext) as MasaDbContextOptions; foreach (var dbContextOptionsExtension in masaDbContextOptions!.Extensions) { if (dbContextOptionsExtension is InMemoryOptionsExtension memoryOptionsExtension) { return memoryOptionsExtension.StoreName; } } return ""; });
Last visit http://localhost:5002/database, Verify whether the current database name is consistent with the modified database name 
common problem
- How to change the default read configuration node ?
Modify user context
UserDbContextAnd increaseConnectionStringNamecharacteristic :[ConnectionStringName("User")]// Custom node name public class UserDbContext : MasaDbContext { public DbSet<User> User { get; set; } public UserDbContext(MasaDbContextOptions options) : base(options) { } }Modify the configuration
appsettings.json{ "ConnectionStrings": { "User": "test"// Instead of from User The node reads the database connection string } }
- In addition to getting from the configuration file , Does it also support getting database connection strings from other places ?
There are currently two ways to change the database connection string .
Method 1: modify Program.cs, And delete appsettings.json Configuration of database connection string
modify
Program.csbuilder.Services.Configure<MasaDbConnectionOptions>(option => { option.ConnectionStrings = new ConnectionStrings(new List<KeyValuePair<string, string>>() { new("User", "test2")// Where the key is the node name , And ConnectionStringName Characteristic Name Keep the values consistent , If not specified ConnectionStringName, It should be DefaultConnection, The value is the database connection string }); });modify
appsettings.jsonTo configure// "ConnectionStrings": { // "User": "test" // },call
databaseMethod , Verify whether the current database istest2

Method 2: rewrite IConnectionStringProvider and IDbConnectionStringProvider And add to DI in
The new class
CustomizeConnectionStringProviderpublic class CustomizeConnectionStringProvider : IConnectionStringProvider { public Task<string> GetConnectionStringAsync(string name = "DefaultConnection") => Task.FromResult (GetConnectionString(name)); public string GetConnectionString(string name = "DefaultConnection") => "test3"; }The new class
CustomizeDbConnectionStringProviderpublic class CustomizeDbConnectionStringProvider : IDbConnectionStringProvider { public List<MasaDbContextConfigurationOptions> DbContextOptionsList { get; } = new() { new MasaDbContextConfigurationOptions("test3") }; }modify
Program.csbuilder.Services.AddSingleton<IConnectionStringProvider,CustomizeConnectionStringProvider>(); builder.Services.AddSingleton<IDbConnectionStringProvider,CustomizeDbConnectionStringProvider>();call
databaseMethod , Verify whether the current database istest3
summary
This article mainly explains MasaDbContext Basic usage and soft deletion 、 How to use data filtering , In the next article, we will explain MasaDbContext How to realize soft deletion 、 Data filtered , And how to realize it when using the database without specifying the database link string mentioned in this article
Source code of this chapter
Assignment05
https://github.com/zhenlei520/MasaFramework.Practice
Open source address
MASA.BuildingBlocks:https://github.com/masastack/MASA.BuildingBlocks
MASA.Contrib:https://github.com/masastack/MASA.Contrib
MASA.Utils:https://github.com/masastack/MASA.Utils
MASA.EShop:https://github.com/masalabs/MASA.EShop
MASA.Blazor:https://github.com/BlazorComponent/MASA.Blazor
If you treat our MASA Framework Interested in , Whether it's code contribution 、 Use 、 carry Issue, Welcome to contact us

边栏推荐
- 高级程序员必知必会,一文详解MySQL主从同步原理,推荐收藏
- [PHP SPL notes]
- 删除文件时提示‘源文件名长度大于系统支持的长度’无法删除解决办法
- 照片选择器CollectionView
- [Oracle] simple date and time formatting and sorting problem
- 利用OPNET进行网络仿真时网络层协议(以QoS为例)的使用、配置及注意点
- 淘宝店铺发布API接口(新),淘宝oAuth2.0店铺商品API接口,淘宝商品发布API接口,淘宝商品上架API接口,一整套发布上架店铺接口对接分享
- When deleting a file, the prompt "the length of the source file name is greater than the length supported by the system" cannot be deleted. Solution
- 论文阅读【MM21 Pre-training for Video Understanding Challenge:Video Captioning with Pretraining Techniqu】
- 实现网页内容可编辑
猜你喜欢

导航栏根据路由变换颜色

论文阅读【Semantic Tag Augmented XlanV Model for Video Captioning】

CentOS 7.9 installing Oracle 21C Adventures

Leetcode 1189 maximum number of "balloons" [map] the leetcode road of heroding
![[binary tree] binary tree path finding](/img/34/1798111e9a294b025806a4d2d5abf8.png)
[binary tree] binary tree path finding

ThinkPHP Association preload with

CVE-2021-3156 漏洞复现笔记

Leetcode (417) -- Pacific Atlantic current problem

K6el-100 leakage relay

Intelligent annotation scheme of entity recognition based on hugging Face Pre training model: generate doccano request JSON format
随机推荐
How can professional people find background music materials when doing we media video clips?
[Oracle] simple date and time formatting and sorting problem
np. random. Shuffle and np Use swapaxis or transfer with caution
Record a pressure measurement experience summary
ssm框架的简单案例
[opencv] image morphological operation opencv marks the positions of different connected domains
基于NCF的多模块协同实例
ThinkPHP Association preload with
数字化如何影响工作流程自动化
Jhok-zbl1 leakage relay
DFS, BFS and traversal search of Graphs
Complete code of C language neural network and its meaning
Torch optimizer small parsing
京东商品详情页API接口、京东商品销量API接口、京东商品列表API接口、京东APP详情API接口、京东详情API接口,京东SKU信息接口
Tencent cloud database public cloud market ranks top 2!
Scheduledexecutorservice timer
Batch size setting skills
《5》 Table
Codeforces Round #416 (Div. 2) D. Vladik and Favorite Game
论文阅读【Semantic Tag Augmented XlanV Model for Video Captioning】