我在项目中使用Entity Framework代码优先迁移。这些迁移之一通过从csv
位于项目目录中的文件中读取数据来填充数据库表。项目结构如下所示:
- Soulution
- Project
- Migrations
- CSVFolder
- file1.csv
- file2.csv
- Migration1.cs
- Migration2.cs
用我的Up()
方法,我得到这些文件是这样的:
public override void Up()
{
var migrationsDir = AppDomain.CurrentDomain.BaseDirectory + "/Migrations/CSVFolder/"; // For some reason, Path.Combine() doesn't work for me here so I manually concatenate the strings.
var templateFiles = Directory.GetFiles(migrationsDir, "*.csv");
foreach (var filename in templateFiles)
{
Sql(); // SQL Insert statement here.
}
}
这在我的开发机上运行良好,但是当我使用Octopus将其部署到测试服务器时,出现未找到路径的异常
找不到路径“ C:\ Octopus \ Applications \ Test \ Solution \ 1.1-alpha21 \ Migrations \ CSVFolder”的一部分。
我已经检查了'drop'文件夹,其中的输出包括Migrations > CSVFolder
。
我尝试了几种其他方法来获取文件夹的路径,但它们可以在本地或在服务器上工作。获得在本地和服务器上都可以使用的路径的最佳方法是什么?
您必须正确设置路径!AppDomain.CurrentDomain.BaseDirectory
将在测试测试运行程序目录的情况下返回,并且在应用程序模式下,您将获得.. \ Bin \ Debug等。您必须检查具有多少目录,直到可以到达所需位置(CSVFolder),然后替换路径或更改它,例如:
var migrationsDir = AppDomain.CurrentDomain.BaseDirectory + "../../Migrations/CSVFolder/"; // For some reason, Path.Combine() doesn't work for me here so I manually concatenate the strings.
您已经注意到,尝试这样做并不容易,因此您可以忘记这种方法,这就是窍门。最好的方法是将cvs文件附加到汇编资源!在迁移期间,您可以按以下方式访问它们:
在Up()中
var file1 = Properties.Resources.File1;
这种方法将确保Sql或Cvs文件始终在运行时附加/加载到程序集。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句