首页 > 解决方案 > SQL Server 更新数据库的列名无效

问题描述

我正在尝试填充类型表,但不断出现错误:

列名无效

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

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的空表。GenreIdname

然后,我尝试使用以下 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 时,无法在表“流派”中插入标识列的显式值。

标签: c#asp.netsql-serverlinq

解决方案


您肯定需要单引号来插入字符串值。从您的错误消息来看,该Id列是一个自动增量(标识)列。所以你不能在不设置的情况下明确定义这些值identity_insert

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

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

推荐阅读