c# - 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
的空表。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_INSERT 设置为 OFF 时,无法在表“流派”中插入标识列的显式值。
解决方案
您肯定需要单引号来插入字符串值。从您的错误消息来看,该Id
列是一个自动增量(标识)列。所以你不能在不设置的情况下明确定义这些值identity_insert
。
最简单的解决方法是Id
从插入中删除 并允许数据库维护这些值。例如:
insert into genres (name) values ('Fantasy')
推荐阅读
- python - 如何在嵌套列表中添加输入值?
- single-sign-on - 将 IdentityServer4 与 Google 一起用作外部 IdP,如何检测用户何时直接退出 Google?
- unit-testing - 用 Jest 测试自执行功能
- react-native - 有什么方法可以根据用户的本地时间使用 React-Native 将 App(UI) 的主题模式动态更改为深色或浅色?
- javascript - 通过更改数组索引来更改精灵
- powershell - 在 PowerShell 脚本中编辑文本文件
- swift - 将图像移动到单独的文件夹 Xcode
- r - 如何根据各种列信息和只有一个唯一 ID 合并 R
- c# - 编组指向结构异常“无法读取或写入受保护内存”的指针数组的指针
- c# - 位图交换真实图像的高度和宽度