.Net核心Dapper连接字符串? [英] .Net CORE Dapper Connection String?

查看:397
本文介绍了.Net核心Dapper连接字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设置我的第一个.NET Core应用程序.我要使用Dapper(1.50.0-rc2)作为ORM.

I am setting up my first .NET Core application. I am going to user Dapper (1.50.0-rc2) for the ORM.

我已将以下内容添加到我的 appsettings.json 文件中.

I have added the following to my appsettings.json file.

"Data": {
    "DefaultConnection": {
        "ConnectionString": "user id=exampleusername;password=examplepassword;Data Source=db.example.com;Database=exampledb;"
    }
},

我对如何获取 ConnectionString 的值感到困惑.由于.NET Core如此新,在线示例无处不在,似乎没有一个实际的例子.

I am confused at how to get the value of ConnectionString. As .NET Core is so new, online examples are all over the place and none seem to actually cover this.

推荐答案

我在GitHub上有一个用于.NET Core的示例控制台应用程序

I have a sample Console App for .NET core on my GitHub repository

设置阶段

var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

构建阶段

Configuration = builder.Build();

使用阶段

Configuration.GetConnectionString("DefaultConnection")

您可以将此值用于Dapper

P.S.

您需要在您的project.json

"Microsoft.Extensions.Configuration": "1.0.0-rc2-final",
"Microsoft.Extensions.Configuration.FileExtensions": "1.0.0-rc2-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final"

已更新

具体解决方案

将配置"设为静态属性,并添加私有设置器

make Configuration static property and add private setter

public static IConfigurationRoot Configuration { get; private set; }

并更改您的扩展名

namespace GamesCore.Extensions 
{
    public class ScoreExtensions 
    { 
        private static string dataConnectionString = Startup.Configuration.GetConnectionString("DefaultConnection"); 
    } 
}

对于.NET Core 2.0,所有内容都是相同的,并且仅更改了项目文件,因此您需要使用以下程序包:

For .NET Core 2.0 everything is same and only project file is changed so you need to use following packages:

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Configuration" Version="2.0.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.0.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.0.2" />
  </ItemGroup>

这篇关于.Net核心Dapper连接字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆