目录
背景
介绍
数据库设置
服务设置
使用DbService的示例
使用DbHelper的示例
存储过程标准
兴趣点
- 下载源9.1 KB
我是一名老软件开发人员,已有20多年的时间,在我的一生中编写了很多独特的代码。在处理数据的实践中,我通常使用SQL Server和存储过程来执行任何复杂的查询。在过去的一年中,我尝试使用Microsoft EF Core框架,但是我总是缺乏以前使用存储过程时的功能。最后,我的耐心耗尽了,我为现代数据操作创建了一个最简单的UkrGuru.SqlJson程序包,现在我想与您分享这些知识...
介绍目前,UkrGuru.SqlJson程序包具有两个类:DbHelper和DbService。
首先,我们需要使用我的样式编码来初始化数据库和存储过程。所有脚本都包含在源存档中。
然后,您需要在appsettings.json文件中进行更新ConnectionString。
"ConnectionStrings": {
"SqlJsonConnection": "Server=localhost;Database=SqlJsonDemo;Integrated Security=SSPI"
}
然后,我们需要在您的ConfigureServices函数中初始化DbService和ConnString:
public void ConfigureServices(IServiceCollection services)
{
// DbService Init
services.AddScoped();
// DbHelper Init
DbHelper.ConnString = Configuration.GetConnectionString("SqlJsonConnection");
}
使用DbService的示例
下面是DbService在代码中使用简单控制器的示例,但请注意,它可以在程序中的任何位置以及具有任何复杂性的过程中使用...
[Route("api/[controller]")]
[ApiController]
public class ContactController : ControllerBase
{
private readonly DbService _db;
public ContactController(DbService db)
{
_db = db;
}
// GET: api/
[HttpGet]
public async Task Get()
{
return await _db.FromProcAsync("Contacts_List");
}
// GET api//1
[HttpGet("{id}")]
public async Task Get(int id)
{
return await _db.FromProcAsync("Contacts_Item", new { Id = id });
}
// POST api/
[HttpPost]
public async Task Post([FromBody] Contact item)
{
return await _db.FromProcAsync("Contacts_Ins", item);
}
// PUT api//5
[HttpPut("{id}")]
public async Task Put(int id, [FromBody] Contact item)
{
await _db.ExecProcAsync("Contacts_Upd", item);
}
// DELETE api//5
[HttpDelete("{id}")]
public async Task Delete(int id)
{
await _db.ExecProcAsync("Contacts_Del", new { Id = id });
}
}
以下是在代码中使用一个简单控制器的DbHelper的示例,但请注意,它可以在您的程序中的任何位置以及任何复杂的过程中使用...
[Route("api/[controller]")]
[ApiController]
public class ContactController : ControllerBase
{
// DbHelper Demo
// POST api//PostGet
[HttpPost("PostGet")]
public async Task PostGet([FromBody] Contact item)
{
using SqlConnection connection = new SqlConnection(DbHelper.ConnString);
await connection.OpenAsync();
var id = await connection.FromProcAsync("Contacts_Ins", item);
return await connection.FromProcAsync("Contacts_Item", new { Id = id });
}
}
UkrGuru.SqlJson 会自动将C#输入参数列表序列化为json并反序列化对象中的结果。
因此,您必须遵循以下要求:
1.您可以使用不带参数或带1个特定参数的存储过程(@Data varchar)
2.如果使用FromProcAsync,那么就需要在JSON格式准备结果与“FOR JSON PATH”表示List或“FOR JSON PATH,WITHOUT_ARRAY_WRAPPER”来表示TEntity
ALTER PROCEDURE [dbo].[Contacts_Ins]
@Data nvarchar(max)
AS
INSERT INTO Contacts (FullName, Email, Notes)
SELECT * FROM OPENJSON(@Data)
WITH (FullName nvarchar(50), Email nvarchar(100), Notes nvarchar(max))
DECLARE @Id int = SCOPE_IDENTITY()
SELECT Id, FullName, Email, Notes
FROM Contacts
WHERE Id = @Id
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
UkrGuru.SqlJson程序包的速度非常快,易于使用,并且远远落后于Microsoft EF Core。
https://www.codeproject.com/Tips/5295154/UkrGuru-SqlJson-Your-Link-Between-SQL-Server-and-N