【问题标题】:Asp.Net core application with ADO.Net example带有 ADO.Net 示例的 Asp.Net 核心应用程序
【发布时间】:2018-07-16 11:40:38
【问题描述】:

我想用ADO.net 创建asp.net core 2.0 MVC 应用程序,我搜索了谷歌/微软,在那里我找到了实体框架的示例,但没有使用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 经验的人。

【问题讨论】:

  • @mm8,是的,以及实体库中的 c 清晰代码,我希望在 ado 方面用于 asp.net 核心。感谢您的帮助
  • 我提供了一个例子。使用 .NET Standard,DAL 本身可以很容易地在 ASP.NET 和 ASP.NET Core 应用程序之间共享。
  • 是的,正在检查和创建应用程序

标签: c# asp.net-core ado.net asp.net-core-2.0


【解决方案1】:

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

在 .NET Core 中,SqlClient 默认不存在。您需要从 NuGet 包管理器添加它。所以请按照以下步骤来实现。

  1. 在 DAL 项目中使用 NuGet 包管理器安装 System.Data.Common
  2. 在 DAL 项目中使用 NuGet 包管理器安装 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;
        }
      }
     }
    

【讨论】:

    【解决方案2】:

    如果您在 .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"
        }
      }
    }
    

    【讨论】:

    • Asp.Net Core 2 及更高版本的最佳答案。
    【解决方案3】:

    我得到了一个关于如何使用配置 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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-15
      • 2018-05-14
      • 2017-06-17
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      相关资源
      最近更新 更多