Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi, I'm new to Entity Framework .Net Core, I'm receiving an error after update of a record.

SqlException: Cannot insert explicit value for identity column in table 'tblAllTransactionsWithDetails' when IDENTITY_INSERT is set to OFF.


I don't know how to get past this one. I set up my table model with a primary [Key]

C#
public class tblAllTransactionsWithDetails
    {

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int internalID { get; set; }
    }


In my Connection Strings override I have the following:

C#
protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
           // modelBuilder.Remove<PluralizingTableNameConvention>();
            modelBuilder.Entity<TransactionsManualTempTable>()
                        .ToTable("TransactionsManualTempTable").ToString();
            modelBuilder.Entity<tblSpreadsheetInput>()
                        .HasNoKey();
            modelBuilder.Entity<tblAllTransactionsWithDetails>()
                        .Property(p => p.internalID)
                        .ValueGeneratedOnAdd();
        }


In my controller I have

C#
_context.tblAllTransactionsWithDetails.Add(tblAllTransactionsWithDetails);


            try
            {
       
                 _context.tblAllTransactionsWithDetails.FromSqlRaw("SET IDENTITY_INSERT dbo.tblAllTransactionsWithDetails ON;");
                 await _context.SaveChangesAsync();
              
            }


It errors on the SaveChangesAsync with the Identity after trying to add a Second record in a row.
I have an AddNewRecord Page, then on click of the button, I want to add/save the record and reload the page, then let the user add another record. It's on the Second record that it errors out.


Thanks,
Heather

What I have tried:

I have tried:
C#
_context.tblAllTransactionsWithDetails.FromSqlRaw("SET IDENTITY_INSERT dbo.tblAllTransactionsWithDetails ON;");

But this doesn't seem to work.
Posted
Updated 12-May-22 9:45am
v2
Comments
Richard Deeming 13-May-22 4:44am    
Using IDENTITY_INSERT in production code is almost always a mistake.

Don't try to disguise the problem like this, since it will only lead to data corruption. Instead, try to work out why you're trying to insert an explicit value for the identity column.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900