带有 ADO.NET 示例的 ASP.NET Core 应用程序

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

我想用

ASP.NET Core 2.0 MVC
创建
ADO.NET
应用程序,我搜索了 google/Microsoft,在那里我找到了使用实体框架的示例,但没有使用 ADO.NET。

我需要,

  1. 从 json 或配置文件中的配置文件读取连接字符串(我知道默认情况下没有 Web.config,但需要从配置文件访问配置条目)。

  2. 为 3 层架构创建 DAL。 (我知道asp.net core不支持ADO.NET,但是)我的要求是使用Sqlconnection,Sqlcommand与ADO.NET中的普通MVC应用程序相同

任何人都可以有一个完整理解的示例或链接吗?我认为这将对每个了解 ASP.NET MVC 但没有 ASP.NET Core 经验的人有所帮助。

c# asp.net-core ado.net asp.net-core-2.0
3个回答
5
投票

我想出了以下解决方案。也许对你有用。

在.NET Core中,SqlClient默认是不存在的。您需要从 NuGet 包管理器添加它。因此,请按照以下步骤来实现这一目标。

  1. 在 DAL 项目中使用 NuGet 包管理器安装 System.Data.Common
  2. 在 DAL 项目中使用 NuGet Package Manager 安装 System.Data.SqlClient

  3. 在您的项目中添加 config.json。就像...

    {
            "name": "asp.net",
            "private": true,
            "dependencies": {
    },
    "connectionString": "data source=*************;initial catalog=****;user id=***;password=****;MultipleActiveResultSets=True;Connection Timeout=300;"
    }
    
  4. 在 DAL 项目中创建一个获取连接字符串的类。在 SetBasePath() 中,您需要设置 DAL 项目的目录路径。

    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    
    namespace MyProject.DAL
    {
    public class SQLDataAccess
    {
    
        protected string ConnectionString { get; set; }
    
        public SQLDataAccess()
        {
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetParent(Directory.GetCurrentDirectory()) + "/MyProject.DAL").AddJsonFile("config.json", false)
                .Build();
    
            this.ConnectionString = configuration.GetSection("connectionString").Value;
        }
    
        private SqlConnection GetConnection()
        {
            SqlConnection connection = new SqlConnection(this.ConnectionString);
            if (connection.State != ConnectionState.Open)
                connection.Open();
            return connection;
        }
    
        public DbDataReader GetDataReader(string procedureName, List<SqlParameter> parameters, CommandType commandType = CommandType.StoredProcedure)
        {
            DbDataReader dr;
    
            try
            {
                DbConnection connection = this.GetConnection();
                {
                    DbCommand cmd = this.GetCommand(connection, procedureName, commandType);
                    if (parameters != null && parameters.Count > 0)
                    {
                        cmd.Parameters.AddRange(parameters.ToArray());
                    }
    
                    dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
    
            return dr;
        }
      }
     }
    

1
投票

如果您在 .NET Standard 2.0 类库中定义 DAL,则可以同时使用

SqlConnection
SqlCommand
,例如:

public class MyDal
{
    private readonly string _connectionString;

    public MyDal(string connectionString)
    {
        _connectionString = connectionString;
    }

    public IEnumerable<string> GetSomeData()
    {
        using (SqlConnection conn = new SqlConnection())
        {
            using (SqlCommand command = new SqlCommand(_connectionString, conn))
            {
        ...
            }
        }
    }
}

然后,您可以从 ASP.NET Core 应用程序添加对库的引用。

使用对依赖注入的内置支持,您可以使用

IConfiguration
:

注入控制器
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddSingleton(Configuration);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
            app.UseDeveloperExceptionPage();

        app.UseMvc();
    }
}

...您可以像这样使用来提取连接字符串:

public class ValuesController : Controller
{
    private readonly IConfiguration _config;

    public ValuesController(IConfiguration config)
    {
        _config = config;
    }

    [HttpGet]
    public IEnumerable<string> Get()
    {
        MyDal dal = new MyDal(_config.GetConnectionString("conn"));
        return dal.GetSomeData();
    }
}

连接字符串本身在

appsettings.json
中定义:

{
"ConnectionStrings": {
  "conn": "Server=localhost;Database=database;Trusted_Connection=True;"
},
"Logging": {
  "IncludeScopes": false,
  "Debug": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "Console": {
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

1
投票

我得到了如何使用配置 json 中的连接字符串的答案。假设我有如下

appsetting.json

{   
    "connectionString": "data source=servername;initial catalog=yourdb;user id=sa;password=pwd;MultipleActiveResultSets=True;"
}

现在我想访问这个连接字符串,所以代码是

using Microsoft.Extensions.Configuration;
using System.IO;

protected string ConnectionString { get; set; }

public GetDBConnString()
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory() + "/").AddJsonFile("config.json", false)
            .Build();

        this.ConnectionString = configuration.GetSection("connectionString").Value;
    }
© www.soinside.com 2019 - 2024. All rights reserved.