[英]Cannot insert explicit value for identity column when identity_insert is set to OFF when auto-increment is already implemented
I have already implemented the auto-increment for database, the identity_insert is set to OFF. 我已经实现了数据库的自动增量,identity_insert设置为OFF。
However, when I tried to insert data into the other columns, I get the "Cannot insert explicit value for identity column in table 'Bookmarks' when IDENTITY_INSERT is set to OFF." 但是,当我尝试将数据插入其他列时,出现“当IDENTITY_INSERT设置为OFF时,无法在表'书签'中为身份列插入显式值”。 error.
错误。 The code below is the table definition:
下面的代码是表定义:
CREATE TABLE [dbo].[Bookmarks] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[carparkId] INT NULL,
[date] DATETIME NULL,
[username] NVARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
FOREIGN KEY ([carparkId]) REFERENCES [dbo].[Carparks] ([id])
); );
The code below shows the inserting of the data and the error occurs on db.SaveChanges(). 下面的代码显示了数据的插入,并且错误发生在db.SaveChanges()上。
public void Insert(Bookmark obj)
{
data.Add(obj);
db.SaveChanges();
}
This is the data i am trying to pass in: 这是我要传递的数据:
public ActionResult Create([Bind(Include = "carparkId,date,username")] Bookmark bookmark)
{
if (ModelState.IsValid)
{
bookmarkGateway.Insert(bookmark);
return RedirectToAction("Index");
}
Any idea how to solve this error without turning on the identity_insert ? 任何想法如何解决此错误而无需打开identity_insert吗? Your help is much appreciated thanks.
非常感谢您的帮助。
From the code you posted seems that error in EF mapping. 从您发布的代码看来,EF映射中的错误。
class BookmarkMap: EntityTypeConfiguration<Bookmark>
{
public BookmarkMap()
{
Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.