Entity Framework 6 个与 DNX 的连接字符串

Entity Framework 6 connection string with DNX

据我了解Entity Framework6,它神奇地实现了来自app.config/web.config 的连接字符串。来自 DbContext 文档,部分备注:

If the parameterless DbContext constructor is called from a derived context, then the name of the derived context is used to find a connection string in the app.config or web.config file

对于无参数构造函数的情况,或者对于具有连接字符串名称的情况:

Instead of using the derived context name, the connection/database name can also be specified explicitly by passing the name to one of the DbContext constructors that takes a string. The name can also be passed in the form "name=myname", in which case the name must be found in the config file or an exception will be thrown.

但是,在 DNX 项目中,我没有 app.config 或 web.config。如何在 DNX 项目中指定 Entity Framework6 中的连接?

至少对于代码优先方法,不需要 app.config 或 web.config。连接字符串可以在任何配置文件中定义,甚至可以没有它——硬编码(这不是一个好的做法)。

In ASP.NET 5 与 EF6 连接字符串可以像往常一样在 config.json 文件中指定。这当然假设从 json 文件加载配置,因为 @Martijn 注意到:

添加两个包到project.json:

"dependencies": {
  "Microsoft.Framework.Configuration.Abstractions": "1.0.0-beta8",
  "Microsoft.Framework.Configuration.Json": "1.0.0-beta8"
}

将 config.json 添加到您的项目:

{
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "Data Source=(local);Database=EfExample;Integrated Security=True"
    }
  }
}

在Program.cs中加载配置(此class在beta8之后可能无效):

[...CODE ...]
using Microsoft.Framework.Configuration;

[...CODE ...]

public class Program
{
    public void Main(string[] args)
    {
     var builder = new ConfigurationBuilder()
            .SetBasePath(".")
            .AddJsonFile("config.json");
[... CODE ...]

现在可以使用

创建 DbContext
 new ApplicationDbContext(Configuration["Data:DefaultConnection:ConnectionString"])

假设你已经有了 ApplicationDbContext 这样的构造函数

    public ApplicationDbContext(string nameOrConnectionString)
        : base(nameOrConnectionString)
    {
    }

如果您想了解更多关于 DNX 配置的信息,我在 post 上有关于它的博客:http://bleedingnedge.com/2015/10/15/configuration-providers/

可以在此处找到有关 ASP.NET 5 和 EF6 的不同配置问题的其他信息(虽然主要集中在 MVC 项目上),包括 mssql、localdb、postgresql 的配置和避免其他 app.config 问题:http://bleedingnedge.com/2015/11/01/entity-framework-6-with-asp-net-5/