【问题标题】:Issues with inserting data with ef core on migration在迁移时使用 ef core 插入数据的问题
【发布时间】:2021-09-29 20:17:24
【问题描述】:

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

迁移中的代码

        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-core database-migration


    【解决方案1】:

    根据您与ef core 一起使用的提供程序,您需要为您的提供程序指定相应的数据类型值。例如:对 SQL Server 使用 int。更多信息:https://www.w3schools.com/sql/sql_datatypes.asp

    【讨论】:

    • 我正在使用 Ngpsql 进行 postgres,我尝试过 int numeric 和 integer
    • 尝试在注释中指定列的数据类型。即Column[Name="filetypeid", TypeName="integer"]。这里有更多信息:entityframeworktutorial.net/code-first/…
    • 没有用。我遇到了同样的错误。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-15
      • 1970-01-01
      • 2018-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多