【问题标题】:App.Config in a class library for data access from WPF and ASP.NET?用于从 WPF 和 ASP.NET 访问数据的类库中的 App.Config?
【发布时间】:2020-11-24 22:55:23
【问题描述】:

我第一次尝试使用 SQL 在我的一个项目中存储数据,我正在使用 this 教程,因为它对我来说最有意义,老实说,我喜欢这些视频,并且讨厌点击数百个糟糕的视频,然后才能找到一个我可以从中学习的视频。

无论如何,我正在制作一个需要访问并保存到我在 MSSMS 中制作的 SQL 数据库的应用程序,我有一个用于逻辑的类库、一个用于数据访问的数据类库和一个 WPF 接口(我也计划添加一个编辑功能较少的ASP界面,但添加Web API,都是为了学习)

在连接 dapper 的视频中,这个家伙设置了一个帮助程序来获取连接字符串,但那是通过配置管理器查找 App.Config(他说它已被烘焙,你只需要添加一个引用,但是现在看来是一个 NuGet 包)。

但是我在任何地方都没有App.config,而且我从来没有使用过它,所以我不知道我是否应该添加它,它会做什么,我会在哪里添加它?还是我现在使用 .NET Core 而不是 .NET Framework 做一些完全不同的事情。

抱歉,帖子太长了,可能还不够清晰,但我在第一个障碍中挣扎,谷歌似乎在这方面毫无用处。

作为旁注,我还计划从我的对象中保存键值对(如Dictionary<string, string>),我最好只为这些对象创建一个新表并存储对象的 Id它与它们自己的列中的键和值相关联吗?

【问题讨论】:

  • 您的“顶层”将具有 ConnectionStrings。所以要么是 Console.exe 应用程序,要么是 web(webapi/webmvc) 等。.netcore 现在有“appsettings.json”

标签: c# sql .net-core data-access-layer class-library


【解决方案1】:

这是一个基本的 dotnet core 命令行 exe

注意,这是本文内容的松散迷你实现:https://docs.microsoft.com/en-us/dotnet/architecture/modern-web-apps-azure/common-web-application-architectures

https://github.com/granadacoder/dotnet-core-on-linux-one/tree/master/src/ConsoleOne

典型的 appsettings.json 内容

https://github.com/granadacoder/dotnet-core-on-linux-one/blob/master/src/ConsoleOne/appsettings.json

{
  "ConnectionStrings": {
    "MyConnectionString": "Data Source=someServer\someInstance,1433;Database=master;User Id=sa;Password=Password1#;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  },
  "AllowedHosts": "*"
}

这个顶层拥有并定义了这些值。在我的示例中,“ConsoleOne”是顶层。

我还有一个 BAL 和 DAL 层。

https://github.com/granadacoder/dotnet-core-on-linux-one/tree/master/src/Bal

https://github.com/granadacoder/dotnet-core-on-linux-one/tree/master/src/Dal

我的示例使用了 Dapper,它会查找连接字符串

https://github.com/granadacoder/dotnet-core-on-linux-one/blob/master/src/Dal/EmployeeDataLayer.cs

public class EmployeeDataLayer : IEmployeeDataLayer
{
    private readonly Microsoft.Extensions.Configuration.IConfiguration config;

    public EmployeeDataLayer(Microsoft.Extensions.Configuration.IConfiguration config)
    {
        this.config = config;
    }

    public IDbConnection Connection
    {
        get
        {
            string connectionString = this.config.GetConnectionString("MyConnectionString");
            return new SqlConnection(connectionString);
        }
    }

    public async Task<Employee> GetByID(int id)
    {
        using (IDbConnection conn = this.Connection)
        {
            string sql = "SELECT ID, FirstName, LastName, DateOfBirth FROM Employee WHERE ID = @ID";
            sql = "SELECT TOP 1 id as ID, 'FName' + name as FirstName, 'LName' + name as LastName, crdate as DateOfBirth FROM sysobjects order by id";
            conn.Open();
            var result = await conn.QueryAsync<Employee>(sql, new { ID = id });
            return result.FirstOrDefault();
        }
    }

    public async Task<ICollection<Employee>> GetByDateOfBirth(DateTime dateOfBirth)
    {
        using (IDbConnection conn = this.Connection)
        {
            string sql = "SELECT ID, FirstName, LastName, DateOfBirth FROM Employee WHERE DateOfBirth = @DateOfBirth";
            sql = "SELECT TOP 3 id as ID, 'FName' + name as FirstName, 'LName' + name as LastName, crdate as DateOfBirth FROM sysobjects order by id";

            conn.Open();
            var result = await conn.QueryAsync<Employee>(sql, new { DateOfBirth = dateOfBirth });
            return result.ToList();
        }
    }
}

(注意,我上面的 DAL 代码并没有打到真正的后端表,这是我做的一个简单的演示)

但回到配置:

我通过将 Configuration 对象“注入”到类中来完成此操作(请参阅构造函数)

使用 dotnet-core,您通常使用内置的 IoC/DI

你可以在这里看到:

https://github.com/granadacoder/dotnet-core-on-linux-one/blob/master/src/ConsoleOne/Program.cs

    private static IServiceProvider BuildDi(IConfiguration config)
    {
        string connectionString = config.GetConnectionString("MyConnectionString");


        return new ServiceCollection()
            .AddSingleton<IEmployeeManager, EmployeeManager>()
            .AddTransient<IEmployeeDataLayer, EmployeeDataLayer>()

            .AddLogging(loggingBuilder =>
            {
                // configure Logging with NLog
                loggingBuilder.ClearProviders();
                loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                loggingBuilder.AddNLog(config);
            })

            .AddSingleton<IConfiguration>(config)
            .BuildServiceProvider();
    }

【讨论】:

  • 我没有控制台应用程序,我是否应该将此 json 添加到我的 WPF 应用程序中,然后当我在解决方案中设置我的 ASP.NET 项目时克隆它?
  • 对。顶层可以是 WPF 应用程序。那么这将引用 BAL 和 DAL。
  • 其实这就是一大堆信息,我想我需要一些时间来理解所有这些,我会回到这里,看看它是如何为我工作的。
【解决方案2】:

我最终只是去了我的 UI 添加 > 新项目 > 应用程序配置文件,称为 App.config 并使用此代码

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <clear/>
        <add name="Thenameasusedinmyapp" connectionString="Server =.; Database = NameofDatabase; Trusted_Connection = True;" providerName="System.Data.SqlClient"/>
    </connectionStrings>
</configuration>

【讨论】:

    猜你喜欢
    • 2015-12-27
    • 2012-03-20
    • 1970-01-01
    • 2016-05-23
    • 2014-02-10
    • 2016-03-23
    • 1970-01-01
    • 2011-08-24
    • 2018-12-18
    相关资源
    最近更新 更多