【问题标题】:Invalid column name for SQL Server update-databaseSQL Server 更新数据库的列名无效
【发布时间】:2018-11-22 03:46:23
【问题描述】:

我正在尝试填充流派表,但不断收到错误:

列名无效

我有一个简单的电影类型类模型。

public class Genre
{
    public int Id { get; set; }
    public string Name { get; set; }
}

一个电影类与这样的类型相关联:

public class Movie
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public Genre Genre { get; set; }

    [Required]
    public DateTime ReleaseDate { get; set; }

    [Required]
    public DateTime DateAdded { get; set; }

    [Required]
    public int  NumInStock { get; set; }
}

在我的 Nuget 控制台中,我运行 add-migration,它为我生成了一个空的 Genre 表,其中包含两列 Idname

然后,我尝试使用以下 SQL 查询填充流派表:

public override void Up()
{
    Sql("INSERT INTO Genres (Id, Name) VALUES (1, Fantasy)");
    Sql("INSERT INTO Genres (Id, Name) VALUES (2, Drama)");
    Sql("INSERT INTO Genres (Id, Name) VALUES (3, Action-Adventure)");
    Sql("INSERT INTO Genres (Id, Name) VALUES (4, Foreign)");
    Sql("INSERT INTO Genres (Id, Name) VALUES (5, Horror)");
    Sql("INSERT INTO Genres (Id, Name) VALUES (6, Romance)");
    Sql("INSERT INTO Genres (Id, Name) VALUES (7, Crime)");
    Sql("INSERT INTO Genres (Id, Name) VALUES (8, Thriller)");
    Sql("INSERT INTO Genres (Id, Name) VALUES (9, Animated)");
    Sql("INSERT INTO Genres (Id, Name) VALUES (10, Western)");
}

不知道我做错了什么。如果我将 'fantasy' 放在引号中(因为它可能需要一个字符串?)然后我会收到这个错误:

当 IDENTITY_INSERT 设置为 OFF 时,无法为表“流派”中的标识列插入显式值。

【问题讨论】:

  • 检查你的Genres表的定义,Id是一个系统生成的列Identity column,没有指定SET INDENTITY_INSERTON,你不能在这个列中插入你自己的值,即使它们是相同的。

标签: c# asp.net sql-server linq


【解决方案1】:

你肯定需要单引号来插入字符串值。从您的错误消息中,Id 列是一个自动增量(身份)列。因此,如果不设置 identity_insert,就无法显式定义这些值。

最简单的解决方法是从插入中删除 Id 并允许数据库维护这些值。例如:

insert into genres (name) values ('Fantasy')

【讨论】:

  • 谢谢。这行得通。诡异的。我之前遵循了一个教程,他们让我手动添加 id - 这就是我尝试在这个教程中这样做的原因。
  • @J.G.Sable 添加迁移时,检查它是否在 Id 字段上创建了身份。您遵循的教程可能没有这样做。很高兴它现在对你有用。
  • @J.G.Sable 这并不奇怪 - 这是正常行为。你只是还没有学会正常的行为。如果一列是标识列,那么在一般情况下插入时不能指定标识的值。所以要解决,不要插入身份。或者关闭身份插入,如图here。或者使该列不是身份列。
【解决方案2】:

作为其他选项,您可以为此表打开SET IDENTITY_INSERT。它允许将显式值插入到表的标识列中。
以及如何标记你应该在单引号中设置字符串值

Sql("SET IDENTITY_INSERT Genres ON");
Sql("INSERT INTO Genres (Id, Name) VALUES (1, 'Fantasy')");
.....
Sql("SET IDENTITY_INSERT Genres OFF");

【讨论】:

    猜你喜欢
    • 2013-09-27
    • 1970-01-01
    • 2012-05-07
    • 2018-04-22
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多