首页 > 解决方案 > 在迁移时使用 ef core 插入数据的问题

问题描述

我正在尝试将自己的代码写入 ef core migration Up 方法,以将一些静态数据插入表中。简而言之,我想这样做。INSERT INTO file_type (filetypeid, filetype) VALUES (10, 'Output File');

迁移中的代码

        migrationBuilder.InsertData(
            "file_type",
            new string[] { "filetypeid", "filetype" },
            new string[] { "integer", "varchar" },
            new object[] { "10", "Output File" });

当我使用上面的代码时,我得到

当前提供程序不支持迁移数据操作中用于列“file_type.filetypeid”的存储类型“整数”。

如果我省略了数据类型参数 (3) 我得到

没有实体类型映射到数据操作中使用的表“file_type”。要么将对应的实体类型添加到模型中,要么在数据操作中指定列类型。

模型

[Table("file_type")]
public class FileType
{
    [Key]
    [Column("filetypeid")]
    public int FileTypeId { get; set; }
    [Column("filetype")]
    public string FileTypes { get; set; }
}

参考我正在使用 https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.migrations.migrationbuilder.insertdata?view=efcore-5.0#Microsoft_EntityFrameworkCore_Migrations_MigrationBuilder_InsertData_System_String_System_String___System_String___System_Object___System_String _

标签: c#entity-framework-coredatabase-migration

解决方案


通过使用解决了它。感谢@Farzan 的帮助。

migrationBuilder.Sql("INSERT INTO file_type (filetypeid, filetype) VALUES (10, 'Output File');", false);


推荐阅读