gpt4 book ai didi

c# - 将连接字符串传递给代码优先 DbContext

转载 作者:IT王子 更新时间:2023-10-29 03:38:19 24 4
gpt4 key购买 nike

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

模型和上下文

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>

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

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)

最佳答案

这里的游戏有点晚了,但另一种选择是:

public class NerdDinners : DbContext
{
public NerdDinners(string connString)
{
this.Database.Connection.ConnectionString = connString;
}
public DbSet<Dinner> Dinners { get; set; }
}

关于c# - 将连接字符串传递给代码优先 DbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4805094/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com