为什么“ ID = 0”?当我尝试在数据库中插入字段为主键时? [英] Why "ID = 0" when I try to insert in database while the field is primary key?
问题描述
我试图在数据库的 BookInfo
表中插入(创建)一本书,但出现此错误:
I am trying to insert (create) a book in the BookInfo
table in database but I get this error:
处理请求时发生未处理的异常。
SqlException:INSERT语句与FOREIGN KEY约束 FK_Book_Categories_BookInfo_BookID冲突。冲突发生在数据库 MyBookShopDB,表 dbo.BookInfo,列 BookID中。
An unhandled exception occurred while processing the request. SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Book_Categories_BookInfo_BookID". The conflict occurred in database "MyBookShopDB", table "dbo.BookInfo", column 'BookID'.
我有具有多对多关系的BookInfo
和类别
。
我正在使用视图模型做这份工作。我认为问题在于,当我跟踪 Create
操作方法时,我会看到 BookID
为 0 ;
And I am using a view model to do the job. I think the problem is that when I trace my Create
action method, then I see that the BookID
is "0"
但是 BookID
被定义为自动增量主键,我不知道为什么它仍为 0。当我尝试创建一本书或将一本书插入数据库时......
But BookID
is defined as an auto-increment primary key and I do not know why it is still "0" when I try to create or insert a book into the database....
有人知道我该怎么做才能解决这个问题?
Does anyone know what should I do to solve this problem?
谢谢!
public async Task<IActionResult> Create(BooksCreateViewModel ViewModel)
{
if (ModelState.IsValid)
{
Book book = new Book()
{
ISBN = ViewModel.ISBN,
Stock = ViewModel.Stock,
Price = ViewModel.Price,
Title = ViewModel.Title,
};
await _context.Books.AddAsync(book);
}
}
这是BookInfo类:
Here is the BookInfo Class:
[Table("BookInfo")]
public class Book
{
[Key]
public int BookID { get; set; }
[Required]
public string Title { get; set; }
public string Summary { get; set; }
public int Price { get; set; }
public int Stock { get; set; }
}
这是迁移类:
migrationBuilder.CreateTable(
name: "BookInfo",
columns: table => new
{
BookID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Title = table.Column<string>(nullable: false),
Summary = table.Column<string>(nullable: true),
Price = table.Column<int>(nullable: false),
Stock = table.Column<int>(nullable: false),
},
SQL
ALTER TABLE [dbo].[Book_Categories] ADD CONSTRAINT [PK_Book_Categories] PRIMARY KEY CLUSTERED ([BookID] ASC,[CategoryID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
推荐答案
在Book实体中,您是否向Book.ID添加了装饰器以通知Entity Framework允许服务器分配值?
In the Book Entity have you added a decorator to Book.ID to inform Entity Framework to allow the Server to assign the value?
类似这样的事情:
public class Book
{
public Book() { }
[DatabaseGenerated(DatabaseGeneratedOption.Identity), Key]
public int ID { get; set; }
public string ISBN { get; set; }
public string Stock { get; set; }
public string Price { get; set; }
public string Title { get; set; }
}
这篇关于为什么“ ID = 0”?当我尝试在数据库中插入字段为主键时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!