【发布时间】:2015-10-07 12:56:53
【问题描述】:
我有一个新的 ASP.NET Web 应用程序,我称之为“Smartifyer”,它一开始是空的。我用 Nuget 添加了 EntityFramework 并创建了一个名为 WordModel 的模型和以下上下文:
public class SmartifyerContext : DbContext
{
public SmartifyerContext()
: base("SmartifyerDatabase")
{
}
public DbSet<WordModel> Words { get; set; }
}
在根目录的Web.config内我有以下配置:
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="SmartifyerDatabase"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\SmartifyerDb.mdf;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
在上下文上运行测试时,Find 方法需要大约 30 秒才能超时并出现以下错误:
System.Data.SqlClient.SqlException:网络相关或 建立连接时发生特定于实例的错误 SQL 服务器。服务器未找到或无法访问。核实 实例名称正确且 SQL Server 配置为 允许远程连接。 (提供者:SQL 网络接口,错误:26 - 定位服务器/指定实例时出错)
我对设置 SQL 连接以及Web.config 中的所有配置的作用知之甚少。如果.mdf 数据库文件不存在,我希望自动生成它,但我不确定如何修改我的配置来做到这一点。
使用解决方案编辑:
我所有的连接配置和数据库都设置正确。我的问题是我正在运行一个使用测试项目的app.config 文件而不是主项目的web.config 的单元测试。将我的web.config 复制并粘贴到测试项目的app.config 中解决了这个问题!
【问题讨论】:
-
我很确定 EF 会创建实体,但不会创建数据库,但有人可能会说不同...
-
在以前使用 EF 的项目中,我使用过的设置是,如果我删除了
.mdf,将重新生成数据库。
标签: c# asp.net sql-server entity-framework