在执行代码优先迁移期间上传图像

Upload an image during the execution of the code-first migration

好的...所以这是我什至不知道是否可能的事情。是否可以在代码优先迁移的初始阶段上传图像文件?例如,在创建具有肖像图像的初始站点用户或管理员用户时,是否可以在该用户的初始创建期间上传该图像?

我在 SO 或网上找不到任何相关的内容甚至可以提出可行的解决方案,所以这可能是第一次尝试这样的事情。

  1. 首先,创建新的迁移文件(或使用现有的)。
  2. Inside Up() 方法,您可以将代码用于 文件上传,以及用于从中删除文件的 Down() 方法代码 回购(如果你想恢复迁移)。

以下是进行远程上传的众多可能方法之一,这是最简单的方法之一:

using (var webClient = new WebClient())
{
   webClient.UploadFile("ftp://localhost/samplefile.jpg", "samplefile.jpg");
}

为此,您应该将 using System.Net; 添加到迁移文件中。此外,显然您需要处理上传权限和凭据,具体取决于您使用的远程仓库类型。

编辑:

使用 File 对象更加简单。这是迁移的完整代码 class:

using System;
using System.Data.Entity.Migrations;
using System.IO;

public partial class MigrationWithFileCopy : DbMigration
{
    public override void Up()
    {
        File.Copy("sourceFile.jpg", "destinationFile.jpg");
    }

    public override void Down()
    {
        File.Delete("destinationFile.jpg");
    }
}