将连接字符串传递给代码优先的 DbContext [英] Pass connection string to code-first DbContext

查看:30
本文介绍了将连接字符串传递给代码优先的 DbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将连接字符串传递给实体框架的代码优先 DbContext?当 DbContext 和 web.config 中的连接字符串在同一个项目中并以相同的方式命名时,我的数据库生成工作正常.但是现在我需要将 DbContext 移动到另一个项目,因此我正在测试将连接字符串传递给它,如下所示:

How do I pass a connection string to entity framework's code-first DbContext? My database generation works correctly when both DbContext and the connection string in web.config is in the same project and named the same way. But now I need to move the DbContext to another project so I'm testing passing a connection string to it as follows:

模型和上下文

public class Dinner
{
    public int DinnerId { get; set; }
    public string Title { get; set; }
}

public class NerdDinners : DbContext
{
    public NerdDinners(string connString)
        : base(connString)
    {
    }
    public DbSet<Dinner> Dinners { get; set; }
}

行动

    public ActionResult Index()
    {
        var db = new NerdDinners(ConfigurationManager.ConnectionStrings["NerdDinnerDb"].ConnectionString);

        var dinners = (from d in db.Dinners
                      select d).ToList();
        return View(dinners);
    }

Web.Config

<connectionStrings>
  <add name="NerdDinnerDb" connectionString="Data Source=|DataDirectory|NerdDinners.sdf" providerName="System.Data.SqlServerCe.4.0"/>    
</connectionStrings>

如果我在分析 db 的操作中设置断点,连接字符串在那里,但它不会创建或找到数据库或任何东西.

If I set a breakpoint in the action an analyze the db, the connection string is there, but it does not create or find the database or anything.

与 SQL Server 建立连接时发生与网络相关或特定于实例的错误.服务器未找到或无法访问.验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接.(提供程序:命名管道提供程序,错误:40 - 无法打开与 SQL Server 的连接)

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

推荐答案

阅读文档后,我不得不传递连接字符串的名称:

After reading the docs, I have to pass the name of the connection string instead:

var db = new NerdDinners("NerdDinnerDb");

这篇关于将连接字符串传递给代码优先的 DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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