IDENTITY_INSERT设置为OFF [英] IDENTITY_INSERT is set to OFF

查看:112
本文介绍了IDENTITY_INSERT设置为OFF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我只想刷新我对EF和LinQ的了解,这就是为什么我创建了一个具有CRUD功能的应用程序。现在的问题是我收到错误

当IDENTITY_INSERT设置为OFF时,无法在表'Book'中为标识列插入显式值。执行Add函数时。我知道我的代码是是的,因为我在以前的练习中总是使用这段代码。



这是我的btnAdd按钮中的代码:

  private   void  CreateBook()
{
var book = new Book();
var addBook = new BookBusinessLayer();
book.Author = txtAuthor.Text;
book.Price = decimal .Parse(txtPrice.Text);
book.Title = txtTitle.Text;
book.Year = txtYear.Text;
book.publisherId = int .Parse(dlistPublisher.SelectedValue); // 这是外键
addBook.AddBook(book);
}





当我看到内部异常时,Book.Id = 0的值

但我没有设置Book.Id的值,因为它是我的主键



我应该如何摆脱这个错误



任何评论和答案将不胜感激:)

解决方案

在数据库级别打开表格上的身份。

SET IDENTITY_INSERT Book ON


使用此查询



  SET   IDENTITY_INSERT  Table_Name  ON  

INSERT INTO Table_Name(ID, name)
VALUES 5 ' David'

SET IDENTITY_INSERT Table_Name OFF


SET BOOK表的以下属性数据库中的Id列



身份规范是



(身份)是



身份增量1



身份种子1

Hi guys,

I just want to refresh my knowledge about EF and LinQ thats why I created an app that has the CRUD functionality.Now the problem is that I got the error
"Cannot insert explicit value for identity column in table 'Book' when IDENTITY_INSERT is set to OFF." when executing Add function.I know my code is correct because I always use this code in my previous exercises.

Here is the code in my btnAdd button:

private void CreateBook()
       {
           var book = new Book();
           var addBook = new BookBusinessLayer();
           book.Author = txtAuthor.Text;
           book.Price = decimal.Parse(txtPrice.Text);
           book.Title = txtTitle.Text;
           book.Year = txtYear.Text;
           book.publisherId = int.Parse(dlistPublisher.SelectedValue);//this is Foreign Key
           addBook.AddBook(book);
       }



And when I see the inner exception the value of Book.Id=0
but I didnt set the value of the Book.Id because it is my Primary Key

How should I get rid of this Error

Any comments and Answers will be appreciated :)

解决方案

Turn on identity on the table at the database level.
SET IDENTITY_INSERT Book ON


use this Query

SET IDENTITY_INSERT Table_Name ON

INSERT INTO Table_Name (ID, name)
VALUES (5, 'David')

SET IDENTITY_INSERT Table_Name OFF


SET Following properties for BOOK’s table Id Column in database

Identity Specification  Yes

(Is Identity)Yes

Identity Increment 1

Identity Seed  1


这篇关于IDENTITY_INSERT设置为OFF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆