通过连接字符串code-第一的DbContext [英] Pass connection string to code-first DbContext

查看:253
本文介绍了通过连接字符串code-第一的DbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何通过一个连接字符串的实体框架的code-第一的DbContext?我的数据库生成正常工作时,都和的DbContext在web.config中的连接字符串是在同一个项目,命名方式相同。但现在我需要到的DbContext移动到另一个项目,所以我测试传递一个连接字符串,如下所示:

型号和放大器;上下文

 公共类晚餐
{
    公众诠释DinnerId {搞定;组; }
    公共字符串名称{搞定;组; }
}公共类NerdDinners:的DbContext
{
    公共NerdDinners(字符串CONNSTRING)
        :基地(CONNSTRING)
    {
    }
    公共DbSet<晚餐及GT;晚餐{搞定;组; }
}

动作

 公众的ActionResult指数()
    {
        变种DB =新NerdDinners(ConfigurationManager.ConnectionStrings [NerdDinnerDb]的ConnectionString);        VAR晚餐=(从D在db.Dinners
                      选择D).ToList();
        返回查看(晚餐);
    }

的Web.Config

 <&是connectionStrings GT;
  <添加名称=NerdDinnerDb的connectionString =数据源= | DataDirectory目录| NerdDinners.sdf的providerName =System.Data.SqlServerCe.4.0/>
< /&是connectionStrings GT;

如果我在动作设置一个断点的分析分贝,连接字符串是存在的,但它并不能创建或找到数据库或任何东西。


  

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



解决方案

阅读文档后,我必须通过连接字符串的名称,而不是:

 变种DB =新NerdDinners(NerdDinnerDb);

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:

Model & Context

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; }
}

Action

    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>

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.

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");

这篇关于通过连接字符串code-第一的DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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