我试图玩EntityFramework6。我使用代码优先方法,并在projectfolder / bin / debug / SchoolContext.mdf中创建了一个数据库。数据库在创建时具有适当的表格,并且我还能够向其添加数据。
我在教程中达到了一个点,我可以使用迁移来更新字段。因此,我从包管理器启用了迁移,从表中删除了一个字段,并使用Add-Migration MigrationName
生成了迁移。生成了迁移,但是当我尝试使用Update-Database
运行它时,我得到以下内容:
CREATE FILE encountered operating system error 5(Access is denied.) while attempting to open or create the physical file 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\SchoolContext.mdf'.
...
问题是它正在寻找错误路径中的mdf文件。我试图找到解决方法,但我无法解决。
正确的道路是:C:\Users\home\Documents\Visual Studio 2017\Projects\Test2\Test2\bin\Debug\SchoolContext.mdf
这是我自动生成的App.config文件+我添加连接字符串的修改。
<?xml version="1.0" encoding="utf-8"?>
<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=bcsfdadsa56145" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="SchoolContext" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|SchoolContext.mdf;Integrated Security=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
我在配置文件中设置DataDirectory
:
internal sealed class Configuration : DbMigrationsConfiguration<Test2.Data.SchoolContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Directory.GetCurrentDirectory());
...
答案 0 :(得分:1)
Code First允许您停止使用基于文件路径的连接字符串,而使用更简单的使用数据库名称的连接字符串:
<connectionStrings>
<add name="SchoolContext"
connectionString="Server=(LocalDB)\MSSQLLocalDB;Database=School;Integrated Security=True;Connect Timeout=30"
providerName="System.Data.SqlClient" />
</connectionStrings>
您不需要配置数据库的路径,只需要数据库名称即可。您可以从AppDomain.CurrentDomain.SetData()
课程中删除Configuration
代码。
确保应用程序运行时以及包管理器控制台在设计时使用正确连接字符串的简单方法:您的DbContext
类应该具有无参数构造函数,该构造函数使用app.config
文件中的连接字符串名称:
public MyDbContext() : base("SchoolContext")
{ ... }
这是指定连接数据的最简单方法。 EF 6提供了其他方法,如in this msdn reference page所述。
您的数据库文件将存储在何处?它不再重要了。 This page解释了这一点。但请注意,LocalDB
不适用于生产系统,仅适用于开发环境。