我想用 ADO.net
创建 asp.net core 2.0 MVC
应用程序,我搜索了谷歌/微软,在那里我找到了 Entity Framework 的例子,但没有 ADO .net.
我需要,
从 json 或配置文件中的配置文件读取连接字符串(我知道默认情况下没有 Web.config,但需要从配置文件访问配置条目)。
为 3 层架构创建 DAL。 (我知道 asp.net core 不支持 ADO.net,但是)我的要求是像 ADO.net 中的普通 MVC 应用程序一样使用 Sqlconnection、Sqlcommand
任何人都可以举个例子或完整理解的链接吗?我认为这对了解 Asp.net MVC 但没有 Asp.net Core 经验的每个人都有帮助。
最佳答案
我想出了以下解决方案。也许对您有用。
在 .NET Core 中,默认情况下不存在 SqlClient。您需要从 NuGet 包管理器添加它。因此,请按照以下步骤来实现这一目标。
- 在您的 DAL 项目中使用 NuGet 包管理器安装 System.Data.Common
在您的 DAL 项目中使用 NuGet 包管理器安装 System.Data.SqlClient
在您的项目中添加 config.json。喜欢...
{ "name": "asp.net", "private": true, "dependencies": { }, "connectionString": "data source=*************;initial catalog=****;user id=***;password=****;MultipleActiveResultSets=True;Connection Timeout=300;" }
在您的 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; } } }
关于c# - 带有 ADO.Net 示例的 Asp.Net 核心应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51360992/