【问题标题】:Read Connection String into configuration without Entity Framewiork DbContext在没有实体 Framewiork DbContext 的情况下将连接字符串读入配置
【发布时间】:2018-12-17 18:38:19
【问题描述】:

我正在开发一个不使用 Entity Framework 的 .NET Core 2.1 应用程序。但我想知道如何将连接字符串读入配置,因为通常的方法需要一个 DBContext 文件(我没有,因为我注意到使用 EF)。

如果我使用的是 EF,我通常会像这样从 appsettings.json 读取连接字符串:

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

没有 DBContext 怎么办?

【问题讨论】:

  • @KirkLarkin - System.Data.SqlClient。我已经编写了自己的数据访问类

标签: asp.net-core


【解决方案1】:

如果您使用的是简单的 ado.net,则不能使用 DBContext。您打开一个连接并改为执行您的查询:

注意 using 语句在这里很重要,以确保正确处理/关闭连接。

 using (SqlConnection connection =
            new SqlConnection(Configuration.GetConnectionString("DefaultConnection")))
        {
            // Create the Command and Parameter objects.
            SqlCommand command = new SqlCommand(queryString, connection);
            command.Parameters.AddWithValue("@pricePoint", paramValue);

            // Open the connection in a try/catch block. 
            // Create and execute the DataReader, writing the result
            // set to the console window.
            try
            {
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine("\t{0}\t{1}\t{2}",
                        reader[0], reader[1], reader[2]);
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }

【讨论】:

  • 我应该检查一下。连接字符串已读入配置。默认情况下,添加到“appsettings.json”的任何内容。感谢您的帮助,@AmanB
猜你喜欢
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
相关资源
最近更新 更多