使用 SQL Server 连接在 ASP.NET Core MVC 项目中添加搜索栏功能

问题描述 投票:0回答:1

我正在创建一个 Web 应用程序来搜索 SQL Server 并显示结果。我在 Visual Studio 中使用 ASP.NET Core 8.0 MVC。我已经建立了从 SQL Server 数据库到我的项目的连接,但我不确定如何实际创建将搜索链接到我的数据库的搜索栏。

我做了很多研究,但大多数都使用 CRUD 或实体框架的某些变体。是否可以使用实体框架在不连接的情况下使用数据库?

这是我的

HomeController
,有我的联系。

using Microsoft.AspNetCore.Mvc;
using Patient_data_search_app.Models;
using System.Diagnostics;

using Microsoft.Extensions.Configuration;
using System.Data.SqlClient;

namespace Patient_data_search_app.Controllers
{
    public class HomeController : Controller
    {
        private readonly IConfiguration configuration;
    
        public HomeController(IConfiguration config)
        {
            this.configuration = config;
        }

        public IActionResult Index()
        {
            string connectionstring = configuration.GetConnectionString("DefaultConnectionString");

            SqlConnection connection = new SqlConnection(connectionstring);
            connection.Open();

            connection.Close();
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

这是我的

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },

  "ConnectionStrings": {
    "DefaultConnectionString": "Server=servername;Database=databasename;Integrated Security=SSPI"
  },
  "AllowedHosts": "*"
}
sql sql-server asp.net-core-mvc
1个回答
0
投票

公共 IActionResult 索引() { 字符串连接字符串 = 配置.GetConnectionString("DefaultConnectionString");

using (SqlConnection connection = new SqlConnection(connectionstring))
{
    connection.Open();

    // Perform database operations here

} // The using statement ensures that the connection is properly closed.

return View();
© www.soinside.com 2019 - 2024. All rights reserved.