; new
{
Id = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
Title = table.Column<string>(nullable: true),
Content = table.Column<string>(nullable: true),
CreateTime = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Topics", x => x.Id);
});
3. 在项目中使用多个上下文
在 Ron.OtherDB 项目中,我们一共创建了两个 Context ,分别是 MySqlForumContext 和 NPgSqlForumContext,这两个 Context 可以在项目中一起使用,互不影响
3.1 在 HomeController 注入两个 Context
private MySqlForumContext mysqlContext;
private NPgSqlForumContext pgsqlContext;
public HomeController(MySqlForumContext mysqlContext, NPgSqlForumContext pgsqlContext)
{
this.mysqlContext = mysqlContext;
this.pgsqlContext = pgsqlContext;
}
``
> 注入的方式非常简单,和其它类型的注入使用方式没有区别,就是简单的在 HomeController 的构造函数中声明这两个 Context 对象即可
#####3.2 使用两个上下文对象进行 CURD 操作
> 下面将演示使用 MySqlForumContext 和 NPgSqlForumContext 进行简单的 CURD 操作,这个操作过程和上一篇的 MSSQL 几乎是完全相同的,代码比较简单,就直接贴上来了
[Route("api/[controller]"), ApiController]
public class HomeController : ControllerBase
{
private MySqlForumContext mysqlContext;
private NPgSqlForumContext pgsqlContext;
public HomeController(MySqlForumContext mysqlContext, NPgSqlForumContext pgsqlContext)
{
this.mysqlContext = mysqlContext;
this.pgsqlContext = pgsqlContext;
}
[HttpGet]
public ActionResult Get()
{
// MySql
var mysqlTopics = this.mysqlContext.Topics.ToList();
// PgSql
var pgsqlTopics = this.pgsqlContext.Topics.ToList();
return new JsonResult(new { mysql = mysqlTopics, pgsql = pgsqlTopics });
}
[HttpPost]
public async Task Post([FromBody] TopicViewModel model)
{
// MySql
this.mysqlContext.Topics.Add(new Topic()
{
Content = model.Content,
CreateTime = DateTime.Now,
Title = model.Title
});
await this.mysqlContext.SaveChangesAsync();
// PgSql
this.pgsqlContext.Topics.Add(new Topic()
{
Content = model.Content,
CreateTime = DateTime.Now,
Title = model.Title
});
await this.pgsqlContext.SaveChangesAsync();
}
[HttpPut]
public async Task Put([FromBody] TopicViewModel model)
{
// MySql
var topic = this.mysqlContext.Topics.Where(f => f.Id == model.Id).FirstOrDefault();
topic.Title = model.Title;
topic.Content = model.Content;
await this.mysqlContext.SaveChangesAsync();
// PgSql
var pgTopic = this.pgsqlContext.Topics.Where(f => f.Id == model.Id).FirstOrDefault();
pgTopic.Title = model.Title;
pgTopic.Content = model.Content;
await this.pgsqlContext.SaveChangesAsync();
}
[HttpDelete("{id}")]
public async Task Delete(int id)
{
// MySql
var topic = this.mysqlContext.Topics.Where(f => f.Id == id).FirstOrDefault();
this.mysqlContext.Topics.Remove(topic);
await this.mysqlContext.SaveChangesAsync();
// PgSql
var pgTopic = this.pgsqlContext.Topics.Where(f => f.Id == id).FirstOrDefault();
this.pgsqlContext.Topics.Remove(pgTopic);
await this.pgsqlContext.SaveChangesAsync();
}
}
```
3.3 打开控制台执行 dotnet run
从结果中可以看到,代码执行正常完成,至此,本文完成
结束语
通过本文学习,我们掌握了以下能力
- 如何在 Asp.NetCore 中使用 EFCore 连接使用 MariaDB/MySql/PostgreSQ