这里我会用英语多解释一点,这样任何人都可以理解。希望这对任何人都有帮助 这是因为 Visual Studio 无法连接到数据库模型。
当您更改扩展 DbContext 的类中的名称和/或路径并且未在 Web.config 文件中更改它(在项目的最外层:根)时,会发生这种情况。
例子:
假设您搭建了 DbContext 代码:
a) 您右键单击项目中的文件夹并添加“ADO.NET 实体数据模型”,并将其命名为“Model1”
你得到以下代码:
public class Model1 : DbContext
{
// Your context has been configured to use a 'Model1' connection string from your application's
// configuration file (App.config or Web.config). By default, this connection string targets the
// 'Skelleton.Models.Model1' database on your LocalDb instance.
//
// If you wish to target a different database and/or database provider, modify the 'Model1'
// connection string in the application configuration file.
public Model1()
: base("name=Model1")
{
}
// Add a DbSet for each entity type that you want to include in your model. For more information
// on configuring and using a Code First model, see http://go.microsoft.com/fwlink/?LinkId=390109.
// public virtual DbSet<MyEntity> MyEntities { get; set; }
}
b) 现在,你认为你刚刚写的名字很糟糕,所以你把它改成 AppContext
您的代码现在如下所示:
public class AppContext : DbContext
{
// Your context has been configured to use a 'AppContext' connection string from your application's
// configuration file (App.config or Web.config). By default, this connection string targets the
// 'Skelleton.Models.AppContext' database on your LocalDb instance.
//
// If you wish to target a different database and/or database provider, modify the 'AppContext'
// connection string in the application configuration file.
public AppContext()
: base("name=AppContext")
{
}
// Add a DbSet for each entity type that you want to include in your model. For more information
// on configuring and using a Code First model, see http://go.microsoft.com/fwlink/?LinkId=390109.
// public virtual DbSet<MyEntity> MyEntities { get; set; }
}
然后,您尝试使用视图构建 CRUD(创建、读取、更新、删除)操作,但失败了!
这是为什么呢?
好吧,如果我们去web.config文件,我们可以看到如下字符串:
<add name="Model1" connectionString="data source=(LocalDb)\v11.0;initial catalog=Skelleton.Models.Model1;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
(此行通常在<add name="DefaultConnection"下方)
这就是问题所在。您需要将 Model1 更改为您提供的名称!
在这种情况下,它应该说“AppContext”而不是“Model1”
它在哪里说:
initial catalog=Skelleton.Models.Model1;
验证:
它是具有类的 .cs 文件的名称
命名空间(或类名之前的一系列名称(点分隔))是正确的。重要的是要注意不要将“.cs”扩展名附加到末尾;只是你的文件名。
它应该看起来像这样:
因为我在内部和外部(内部和文件名)都更改了类的名称,并且没有更改了它的位置,我只是将其重命名为 AppContext
完成后。你可以正常使用脚手架;)
希望这会有所帮助!