NET Core Web API可以使用SqlSugar来访问和操作数据库
在项目中添加以下NuGet包:
SqlSugarCore Microsoft.AspNetCore.Authentication.JwtBearer Swashbuckle.AspNetCore
您可以使用以下命令在Visual Studio的NuGet包管理器控制台中安装这些包:
Install-Package SqlSugarCore Install-Package Microsoft.AspNetCore.Authentication.JwtBearer Install-Package Swashbuckle.AspNetCore
定义一个名为Product的实体类,如下所示:
public class Product { [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } }
在Startup.cs文件中配置SqlSugar,如下所示:
public void ConfigureServices(IServiceCollection services) { //注册SqlSugar services.AddSingleton<ISqlSugarClient>(s => { SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig() { DbType = SqlSugar.DbType.Sqlite, ConnectionString = "DataSource=sqlsugar-dev.db", IsAutoCloseConnection = true, }, db => { //单例参数配置,所有上下文生效 db.Aop.OnLogExecuting = (sql, pars) => { }; }); return sqlSugar; }); // 添加身份验证和授权服务 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; }); // 添加Swagger服务 services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); var securityScheme = new OpenApiSecurityScheme { Name = "Authorization", BearerFormat = "JWT", Scheme = "bearer", Description = "Specify the authorization token.", In = ParameterLocation.Header, Type = SecuritySchemeType.Http }; options.AddSecurityDefinition("Bearer", securityScheme); options.AddSecurityRequirement(new OpenApiSecurityRequirement { { securityScheme, Array.Empty<string>() } }); }); // 添加MVC服务 services.AddControllers(); }
注意,上面的代码将SqlSugar配置为使用SQL Server数据库,并使用属性初始化程序模式来定义实体类的主键和自增属性。
创建一个名为ProductsController的控制器,如下所示:
[Authorize] [ApiController] [Route("api/[controller]")] public class ProductsController : ControllerBase { private readonly ISqlSugarClient _db; public ProductsController(ISqlSugarClient db) { _db = db; } [HttpGet] public async Task<IActionResult> Get() { var products = await _db.Queryable<Product>().ToListAsync(); return Ok(products); } [HttpPost] public async Task<IActionResult> Post(Product product) { await _db.Insertable(product).ExecuteCommandAsync(); return CreatedAtAction(nameof(Get), new { id = product.Id }, product); } [HttpPut("{id}")] public async Task<IActionResult> Put(int id, Product product) { if (id != product.Id) { return BadRequest(); } await _db.Updateable(product).ExecuteCommandAsync(); return No } }
2016 © donet5.comApache Licence 2.0