如何在没有实体框架的情况下连接到ASP.NET Core中的数据库?

编程入门 行业动态 更新时间:2024-10-28 11:33:29
本文介绍了如何在没有实体框架的情况下连接到ASP.NET Core中的数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在没有实体框架的情况下从ASP.NET Core和Angular连接到数据库?

How can I connect to a database from ASP.NET Core and Angular without Entity Framework?

"ConnectionStrings": { "DefaultParkingConnection": "Server=DESKTOP-CD0M0C3\\SQLEXPRESS;Database=ParkingSystem2;Trusted_Connection=True;MultipleActiveResultSets=true;User ID=sa;Password=P@ssw0rd" },

如何在Web API控制器中获取连接字符串?

How can I get connection string in Web API controller?

string constr = ConfigurationManager.ConnectionStrings["DefaultParkingConnection"].ConnectionString;

推荐答案

ASP.Net Core与ASP.Net的工作原理不同,因此您需要将appsettings.json中定义的连接字符串映射到要在整个过程中访问的类或变量.应用程序.请尝试以下方法.创建appSettings.json:

ASP.Net Core works different than ASP.Net, so you need to map the connection strings defined in appsettings.json to a class or variable to be accessed throughout the application. Try the following approach. Create appSettings.json:

{ "ConnectionStrings": { "DefaultParkingConnection": "Server=DESKTOP-CD0M0C3\\SQLEXPRESS;Database=ParkingSystem2;Trusted_Connection=True;MultipleActiveResultSets=true;User ID=sa;Password=P@ssw0rd" } }

创建一个新类ConnectionStrings.cs以将appSettings.json中定义的连接字符串映射到它:

Create a new class ConnectionStrings.cs to map the connection strings defined in appSettings.json to it:

using System; namespace Test { public class ConnectionStrings { public string DefaultParkingConnection{ get; set; } } }

在Startup.cs中,编写以下代码:

public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { this.Configuration = configuration; } public void ConfigureServices(IServiceCollection services) { //Map the configuration var connectionSection = Configuration.GetSection("ConnectionStrings"); services.Configure<ConnectionStrings>(connectionSection ); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // Configure } }

现在在控制器中,您可以轻松使用它而无需创建类的实例:

Now in controllers, you can easily use it without creating the instance of the class:

using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; namespace Test.Controllers { [ApiController] [Route("api/account")] public class AccountController : ControllerBase { private readonly ConnectionStrings connectionStrings; public AccountController(IOptions<ConnectionStrings> connectionStrings) { this.connectionStrings = connectionStrings.Value; } [HttpGet, Route("test")] public IActionResult Test() { return Ok("test"); } } }

更多推荐

如何在没有实体框架的情况下连接到ASP.NET Core中的数据库?

本文发布于:2023-10-17 11:14:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1500730.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:连接到   实体   框架   情况下   数据库

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!