当前位置:网站首页>5. Data access - entityframework integration
5. Data access - entityframework integration
2022-07-05 18:46:00 【InfoQ】
Preface
MasaEntityFrameworkMasaDbContext 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.Tools
dotnet 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.5
> install `Swashbuckle.AspNetCore` For the convenience of passing `Swagger` To operate the service
> install `Microsoft.EntityFrameworkCore.InMemory` It's for convenience , So use an in memory database , If you need to use other databases , Please install the corresponding package by yourself
> install `Microsoft.EntityFrameworkCore.Tools` To use CodeFirst Create database
- The new class
User
public 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.cs
public class UserDbContext : MasaDbContext
{
public DbSet<User> User { get; set; }
public UserDbContext(MasaDbContextOptions options) : base(options)
{
}
}
> `UserDbContext` Instead of inheritance `MasaDbContext`, And add a parameter constructor , Parameter type is `MasaDbContextOptions`
> When there are multiple DbContext when , It needs to be inherited `MasaDbContext<TDbContext>`, The constructor parameter type is changed to `MasaDbContext<TDbContext>`
- The new class
AddUserRequestAs a parameter for adding users
public 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 addedSwaggerSupport
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
SwaggerPostman- 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 CodeFirst
app.MigrateDbContext<UserDbContext>((context, services) =>
{
});
> Unwanted CodeFirst, Code generation is not supported, and the database cannot be added
- test
MasaDbContext, modifyProgram.cs
app.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 `add` Then create a new user , After performing `list` Get more than one user data , Then prove `MasaDbContext` Correct use
How to use soft delete
- Choose
Assignment.MasaEntityFrameworkAnd installMasa.Contrib.Data.Contracts.EF
dotnet add package Masa.Contrib.Data.Contracts.EF --version 0.4.0-rc.4
- Modify 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 for `IsDeleted` Attribute addition set Support ( It can be private set;)
- modify
Program.cs, And enable data filtering
builder.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 method
app.MapDelete("/delete", (UserDbContext dbContext, int id) =>
{
var user = dbContext.Set<User>().First(u => u.Id == id);
dbContext.Set<User>().Remove(user);
dbContext.SaveChanges();
});
addlistdeletelistHow to temporarily disable soft deletion 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 data
- The 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.InMemory
dotnet add package Masa.Contrib.Data.EntityFrameworkCore.InMemory --version 0.4.0-rc.4
> Install 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 istest
app.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 "";
});
http://localhost:5002/database
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 ?
Program.csappsettings.json- modify
Program.cs
builder.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

IConnectionStringProviderIDbConnectionStringProvider- The new class
CustomizeConnectionStringProvider
public class CustomizeConnectionStringProvider : IConnectionStringProvider
{
public Task<string> GetConnectionStringAsync(string name = "DefaultConnection") => Task.FromResult (GetConnectionString(name));
public string GetConnectionString(string name = "DefaultConnection") => "test3";
}
- The new class
CustomizeDbConnectionStringProvider
public class CustomizeDbConnectionStringProvider : IDbConnectionStringProvider
{
public List<MasaDbContextConfigurationOptions> DbContextOptionsList { get; } = new()
{
new MasaDbContextConfigurationOptions("test3")
};
}
- modify
Program.cs
builder.Services.AddSingleton<IConnectionStringProvider,CustomizeConnectionStringProvider>();
builder.Services.AddSingleton<IDbConnectionStringProvider,CustomizeDbConnectionStringProvider>();
- call
databaseMethod , Verify whether the current database istest3
summary
MasaDbContextMasaDbContextSource code of this chapter
Open source address

边栏推荐
- SAP feature description
- What are the cache interfaces of nailing open platform applet API?
- 怎么自动安装pythn三方库
- 技术分享 | 常见接口协议解析
- 5. 数据访问 - EntityFramework集成
- 【HCIA-cloud】【1】云计算的定义、什么是云计算、云计算的架构与技术说明、华为云计算产品、华为内存DDR配置工具说明
- Case sharing | integrated construction of data operation and maintenance in the financial industry
- 集合处理的利器
- 使用文件和目录属性和属性
- 中文版Postman?功能真心强大!
猜你喜欢

Oracle 中文排序 Oracle 中文字段排序
![[HCIA cloud] [1] definition of cloud computing, what is cloud computing, architecture and technical description of cloud computing, Huawei cloud computing products, and description of Huawei memory DD](/img/b8/624799e4bf788e4476b155486f478b.png)
[HCIA cloud] [1] definition of cloud computing, what is cloud computing, architecture and technical description of cloud computing, Huawei cloud computing products, and description of Huawei memory DD

2022最新Android面试笔试,一个安卓程序员的面试心得

Oracle日期格式转换 to_date,to_char,to_timetamp 相互转换

How much does the mlperf list weigh when AI is named?

2022最新中高级Android面试题目,【原理+实战+视频+源码】

基于can总线的A2L文件解析(3)

使用JMeter录制脚本并调试

技术分享 | 接口测试价值与体系

How to write good code defensive programming
随机推荐
Quickly generate IPA package
Logical words in Articles
企业级数据安全,天翼云是这样理解的
跨境支付平台 XTransfer 的低代码实践:如何与其他中台融合是核心
ICML2022 | 长尾识别中分布外检测的部分和非对称对比学习
金太阳开户安全吗?万一免5开户能办理吗?
《ClickHouse原理解析与应用实践》读书笔记(5)
线性表——抽象数据类型
New words new words new words new words [2]
The origin of PTS, DTS and duration of audio and video packages
Chinese postman? Really powerful!
Introduction to Resampling
buuctf-pwn write-ups (9)
MYSQL中 find_in_set() 函数用法详解
SAP 特征 特性 说明
音视频包的pts,dts,duration的由来.
How to choose the most formal and safe external futures platform?
LeetCode 6111. Spiral matrix IV
2022年5月腾讯云开发者社区视频月度榜单公布
The 11th China cloud computing standards and Applications Conference | China cloud data has become the deputy leader unit of the cloud migration special group of the cloud computing standards working
