我想玩弄EntityFramework6。我使用的是代碼優先的方法,並且在我的projectfolder/bin/debug/SchoolContext.mdf中創建了一個數據庫。數據庫在創建時有適當的表格,我也可以向其添加數據。訪問被拒絕,同時嘗試遷移EntityFramework6 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());
...
您確定配置已被隔離嗎?我是因爲內心而問的。你是否在'Database.SetInitializer'上指定它? – bubi
我在c#中整個遷移和數據庫的經驗是有限的。我不記得在任何地方使用set初始化器,但是如果我在配置中放置了一個斷點並且我運行了該項目,它就會停止。 –
我認爲DataDirectory不是正確的方法。我不知道你的要求,但你也可以創建一個指定連接的上下文或以其他幾種方式。檢查此https://stackoverflow.com/questions/29440405/entity-framework-6-set-connection-string-runtime – bubi