Flodpanter
Flodpanter

Reputation: 189

DbUpdateConcurrencyException when inserting a single row

I cannot insert a row in the table defined below. I have to conform to the table´s composite primary key. When using Entity Framework to insert a single row into the table, I get a DbUpdateConcurrencyException. Digging a bit deeper into the exception I see "OriginalValues cannot be used for entities in the Added state."

Below is my code for addding the row as well as the table schema.

c# code:

Entities.Entry(new jotch_krdtrans() {Kred = 1, Regdato = DateTime.Now}).State = EntityState.Added;
Entities.SaveChanges();

SQL table schema:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[jotch_krdtrans](
    [Kred] [decimal](12, 0) NOT NULL,
    [Regdato] [datetime] NOT NULL,
    [Autonum] [decimal](18, 0) IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_jotch_krdtrans] PRIMARY KEY CLUSTERED 
(
    [Kred] ASC,
    [Regdato] ASC,
    [Autonum] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

I have tried setting the ProviderManifestToken to "2005" in my edmx-file and this seems to make it work. However I would prefer a more detailed explanation why this makes it work. What changed between 2005 and 2008 in relation to my insert example? I am hoping for a deeper understanding.

Thanks in advance.

Upvotes: 2

Views: 839

Answers (1)

You must use datetime2(7) instead of datetime in your Database table.

You must be aware of how Entity Framework handle keys in your table. In my code I set the HasDatabaseGeneratedOption. It can be otherwise in your code.

 public class IceCatCategoryMap : EntityTypeConfiguration<IceCatCategory>
 {
    public IceCatCategoryMap()
    {
        ToTable("SemlerServices_IceCatCategory");
        HasKey(m => m.Id);
        Property(m => m.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
    }
}   

Upvotes: 1

Related Questions