【问题标题】:What is the best way to find directory path from an EF migration script?从 EF 迁移脚本中查找目录路径的最佳方法是什么?
【发布时间】:2016-08-11 01:31:38
【问题描述】:

我在我的项目中使用实体框架代码首次迁移。其中一个迁移通过从位于项目目录中的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

我尝试了几种不同的方法来获取文件夹的路径,但它们可以在本地或服务器上工作。获取在本地和服务器上都可以使用的路径的最佳方法是什么?

【问题讨论】:

    标签: c# .net entity-framework entity-framework-migrations


    【解决方案1】:

    您必须正确设置路径! 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 文件附加到程序集资源中!在迁移过程中,您可以通过以下方式访问它们:

    在向上()中

    var file1 = Properties.Resources.File1;
    

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

    【讨论】:

    • “你必须检查你有多少目录才能到达所需的位置”——这正是问题陈述。老实说,我真的不想将它们作为资源嵌入,但似乎这是我必须确保在两种情况下都能正确处理的最佳方式。目前,我使用Directory.GetDirectories(AppDomain.CurrentDomain.BaseDirectory, "CSVFolder")[0] 解决了这个问题。这可行,但假设不会有多个名为“CSVFolder”的目录。
    【解决方案2】:

    这对我有用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-02
      • 2019-08-20
      • 1970-01-01
      • 2019-12-14
      • 2017-03-08
      • 2010-10-09
      相关资源
      最近更新 更多