简体   繁体   中英

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.

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." 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().

    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 ? Your help is much appreciated thanks.

From the code you posted seems that error in EF mapping.

class BookmarkMap: EntityTypeConfiguration<Bookmark>
{
    public BookmarkMap()
    {
        Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM