我有一个解决方案,其中包含一个 MVC 项目和 Windows 类库项目,该项目使用 Entity Framework 并且是数据访问层。我尝试使用以下包管理器控制台行启用迁移 启用迁移 -ProjectName PortlandRoad.DAL -ContextTypeName PortlandRoadDBContext -Force
我尝试使用以下行更新数据库 更新数据库-详细-强制
如果我使用 mvc 项目作为启动项目来执行此操作,它可以工作,但使用 mvc 项目 web.config 中的连接字符串。如果我使用 dAL 项目作为启动项目执行此操作,我会收到以下错误:
发生文件激活错误。物理文件名“\PortlandRoadDB.mdf”可能不正确。诊断并更正其他错误,然后重试该操作。 创建数据库失败。无法创建列出的某些文件名。检查相关错误。
我的 DAL 项目的 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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!--<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />-->
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=PortlandRoadDB;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\PortlandRoadDB.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
任何人都可以告诉我如何纠正这个问题,以便迁移专门针对 dal 项目工作,而不依赖于作为启动项目的 MCV 项目
谢谢
最佳答案
我在 WPF 项目中遇到了同样的问题。 我认为你有两个选择。
选项 1 在 Windows 项目启动时,尝试使用
指定数据库的正确路径AppDomain.CurrentDomain.SetData("DataDirectory","your\physical\path");
这样,您将遇到相同的错误,但您的迁移仍然可以应用于您的主体数据库。
选项 2 找到一种方法来动态替换此 |DataDirectory|在启动应用程序之前在您的 app.config 文件中。 (.bat 或 .ps 或...)。
另一种选择:不好的选择。 在运行迁移之前,将 DataDirectory 的路径更改为 app.config 中的物理临时路径(此文件将帮助您保持最新的迁移历史记录) 在启动应用程序之前,将临时文件路径替换为 |DataDirectory|并在启动时使用 App.config 更改此参数 通过此解决方案,如果您计划部署应用程序,您将跟踪所有迁移,以便预测 future 的数据库修改。
瞧。
关于entity-framework - Entity Framework 代码优先从单独的 Windows 类库迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17517186/