gpt4 book ai didi

c# - EF 连接字符串错误

转载 作者:太空宇宙 更新时间:2023-11-03 16:02:43 26 4
gpt4 key购买 nike

我在 web.config 文件中的连接字符串:

<connectionStrings>
<add name="DefaultConnection"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-EFcodefirst-20131213155231;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-EFcodefirst-20131213155231.mdf" />
</connectionStrings>

我的上下文文件

namespace EFcodefirst.Models
{
public class SampleContext: DbContext
{
public DbSet<EFcodefirst.Models.Customer> Customers { get; set; }
}
}

我的 Controller

SampleContext dbContext = new SampleContext();
var customerList = dbContext.Customers.ToList();
return View(customerList);

这里是错误

An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.

请帮我解决这个问题

最佳答案

看起来您正在尝试在 ASP.NET 成员使用的同一文件中创建数据库,并且您的计算机上没有安装 SQLEXPRESS(否则 Entity Framework 将使用 YourNamespace.SampleContext 创建数据库> SQLEXPRESS 数据库中的名称)。因此,只需添加另一个指向另一个数据库文件的连接字符串:

<connectionStrings>
<add name="SampleContext"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Sample;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Sample.mdf" />
<add name="DefaultConnection"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-EFcodefirst-20131213155231;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-EFcodefirst-20131213155231.mdf" />
</connectionStrings>

注意:如果您不希望连接字符串与您的上下文类同名,您可以将连接字符串名称提供给基础上下文类的构造函数:

public class SampleContext: DbContext
{
public SampleContext()
: base("AnotherConnectionStringName")
{
}

public DbSet<EFcodefirst.Models.Customer> Customers { get; set; }
}

关于c# - EF 连接字符串错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20604723/

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