代码之家  ›  专栏  ›  技术社区  ›  J.G.Sable

SQL Server更新数据库的列名无效

  •  0
  • J.G.Sable  · 技术社区  · 6 年前

    我试图填充一个类型表,但不断地得到一个错误:

    列名无效

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

    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 我的桌子有两列, Id 和; name .

    然后,我尝试用这个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\u insert设置为off时,无法在表“genres”中插入identity列的显式值。

    2 回复  |  直到 6 年前
        1
  •  2
  •   sgeddes    6 年前

    您肯定需要单引号来插入字符串值。从您的错误消息中, Id 列是自动递增(标识)列。因此,如果不设置 identity_insert .

    最简单的解决方法是移除 身份证件 并允许数据库维护这些值。例如:

    insert into genres (name) values ('Fantasy')
    
        2
  •  1
  •   Alexcei Shmakov    6 年前

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

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