从EF迁移脚本中查找目录路径的最佳方法是什么?

本文关键字:路径 最佳 方法 是什么 迁移 EF 脚本 查找 | 更新日期: 2023-09-27 18:01:45

我在我的项目中使用实体框架代码首先迁移。其中一个迁移是通过从位于项目目录中的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: '章鱼' '测试解决方案' ' 1.1的应用程序-alpha21 '迁移' CSVFolder"。

我已经检查了'drop'文件夹,那里的输出包括Migrations > CSVFolder

我尝试了几种不同的方法来获得文件夹的路径,但它们要么在本地工作,要么在服务器上工作。获得既能在本地工作又能在服务器上工作的路径的最佳方法是什么?

从EF迁移脚本中查找目录路径的最佳方法是什么?

您必须正确设置路径!在测试运行程序目录的情况下,AppDomain.CurrentDomain.BaseDirectory将返回,并且在应用程序模式下,您将得到…' Bin '调试等。您必须检查您有多少目录,直到您可以到达所需的位置(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文件附加到程序集资源中!在迁移期间,您可以像下面这样访问它们:

在()

var file1 = Properties.Resources.File1;

此方法将保证Sql或Cvs文件始终在运行时附加/加载到程序集。

这对我有用

AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory