asp.net core > entity-framework-core-dbcontext （作成中）



SampleContext側に入れるのが良いのか、
App側で設定を行うのが良いのか、悩み中
ベストプラクティスを教えてほしい。


[Configuration.GetConnectionString("BloggingDatabase")](https://docs.microsoft.com/ja-jp/ef/core/miscellaneous/connection-strings)

[ASP.NET Core の構成 | Microsoft Docs](https://docs.microsoft.com/ja-jp/aspnet/core/fundamentals/configuration/index?view=aspnetcore-2.1&tabs=basicconfiguration)


### appsettings.json

```js:appsettings.json
{
  "ConnectionStrings": {
      "BloggingDatabase": "Server=yourip; Database=yourdbname; User Id=yourusername; Password=yourpassword; Pooling=true;",
      "Db2ConnectionString": "Database=yourdbname;UserID=yourusername;Password=yourpassword;Server=yourip:yourport",
      "SomeOtherKey": "SomeOtherValue"
  }
}

```


DB Contextファイルの編集

### SampleContext

AppSettingsJsonクラスの追加
SampleContext.csの先頭らへんに以下を追加

```csharp:SampleContext.cs
public static class AppSettingsJson
{
    public static string ApplicationExeDirectory()
    {
        var location = System.Reflection.Assembly.GetExecutingAssembly().Location;
        var appRoot = Path.GetDirectoryName(location);

        return appRoot;
    }

    public static IConfigurationRoot GetAppSettings()
    {
        string applicationExeDirectory = ApplicationExeDirectory();

        var builder = new ConfigurationBuilder()
        .SetBasePath(applicationExeDirectory)
        .AddJsonFile("appsettings.json");

        return builder.Build();
    }
}
```



```csharp:SampleContext.cs

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{

    if (!optionsBuilder.IsConfigured)
    {
        var Configuration = AppSettingsJson.GetAppSettings();
        var connectionString = Configuration.GetConnectionString("BloggingDatabase");
        optionsBuilder.UseSqlServer(connectionString);
    }
}

```


### SampleServiceTest

```csharp:SampleServiceTest.cs

[TestClass]
public class SampleServiceTest
{

    private SampleContext context;
    private static IConfiguration Configuration { get; set; }

    public SampleServiceTest()
    {
        //var builder = new ConfigurationBuilder()
        //    .SetBasePath(Directory.GetCurrentDirectory())
        //    .AddJsonFile("appsettings.Development.json");

        //Configuration = builder.Build();
        //var connectionString = Configuration.GetConnectionString("BloggingDatabase");

        //var optionsBuilder = new DbContextOptionsBuilder<SampleContext>();
        //optionsBuilder.UseSqlServer(connectionString);
        //context = new SampleContext(optionsBuilder.Options);
        
        context = new SampleContext();
    }


    [TestMethod]
    public void GetByIDAsync_Test()
    {
        var id = 1;
        var result = SampleService.GetByIDAsync(context, id).Result;
        Assert.IsNotNull(result);
    }

}

```









[Entity Framework Core DbContext](http://www.entityframeworktutorial.net/efcore/entity-framework-core-dbcontext.aspx)


[DbContext - EF Core の構成 | Microsoft Docs](https://docs.microsoft.com/ja-jp/ef/core/miscellaneous/configuring-dbcontext)

[c# - .NET Core get connection string from appsettings.json - Stack Overflow](https://stackoverflow.com/questions/40218850/net-core-get-connection-string-from-appsettings-json)