gpt4 book ai didi

asp.net-mvc-3 - 使用 MVC 3 ASP.net 连接到 SQL Server 2008

转载 作者:行者123 更新时间:2023-12-04 06:01:09 25 4
gpt4 key购买 nike

我是 ASP.net 的 MVC 3(使用 VB)的新手,我正在尝试创建一个可以连接到 SQL 2008 服务器数据库的应用程序。我已经阅读了一个教程(Microsoft ASP.net 的 Movie DB 教程),但该教程使用的是 SQL 精简版。我很难连接。我是否正确假设一旦我创建了一个模型,我应该能够通过更改 Web.config 文件中的连接字符串来连接到 SQL 2008,该文件位于应用程序文件夹的根目录?我从 App_Data 文件夹中删除了 sql ce 数据库。在 Microsoft SQL Server Management Studio 中,我创建了一个新数据库。然后我将它添加到我的 Web.config 文件中:

      <connectionStrings>
<add name="ConnectionName"
providerName="System.Data.SqlClient"
connectionString="Data Source=DELERIUM-PC;Initial Catalog=iDjItDb;Integrated Security=True" />
</connectionStrings>

当我运行应用程序并尝试查看与模型关联的 Controller 时,出现此错误:

The model backing the 'iDjItDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.



我必须做什么才能连接和使用 2008 SQL 数据库?

谢谢
杰森

最佳答案

您可以删除 IncludeMetadataConvention在您的上下文类中,如果您确定您的模型与数据库兼容。

public class iDjItDBContext : DBContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
}
}

否则你需要在 Application_Start() 中设置初始化器您的方法 Global.asax.cs文件。
Database.SetInitializer<iDjItDBContext>(
new DropCreateDatabaseIfModelChanges<iDjItDBContext>());

否则你可以拿 Migrations外部工具将生成更改脚本的选项。

编辑
将连接字符串名称更改为 iDjItDBContext以便名称与 DbContext 匹配姓名。
<connectionStrings>
<add name="iDjItDBContext"
providerName="System.Data.SqlClient"
connectionString="Data Source=DELERIUM-PC;Initial Catalog=iDjItDb;Integrated Security=True" />
</connectionStrings>

或者在您的上下文中创建一个构造函数并传递连接字符串的名称。
public class iDjItDBContext : DBContext
{
public iDjItDBContext() : base("ConnectionName")
{
}
}

关于asp.net-mvc-3 - 使用 MVC 3 ASP.net 连接到 SQL Server 2008,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8887921/

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