简体   繁体   中英

entity framework 6 can't insert record

if I define a sequence and a table like this:

CREATE SEQUENCE [dbo].[seq-test] 
 AS [bigint]
 START WITH 0
 INCREMENT BY 1
 MINVALUE -9223372036854775808
 MAXVALUE 9223372036854775807
 CACHE 
GO


CREATE TABLE [dbo].[testTab] 
(
    [iden] [bigint] NOT NULL DEFAULT (NEXT VALUE FOR [seq-test]),
    [name1] [nchar](10) NULL,
    [name2] [nchar](10) NULL,
    PRIMARY KEY CLUSTERED 
    (
    [iden] ASC
    )
) ON [PRIMARY]

and then try to insert data using EF 6:

testTab d = new testTab();
d.name1 = "sss";

using (var db = new ABEntities2())
{
    db.testTabs.Add(d);
    db.SaveChanges();
}

and I set StoreGeneratedPattern to Identity for iden column, it doesn't behave as it should, Exception thrown by SaveChanges is DbUpdateConcurrencyException :

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

what am I doing wrong?

generated testTabs:

<EntitySetMapping Name="testTabs">
  <EntityTypeMapping TypeName="ABModel.testTab">
    <MappingFragment StoreEntitySet="testTab">
      <ScalarProperty Name="iden" ColumnName="iden" />
      <ScalarProperty Name="name1" ColumnName="name1" />
      <ScalarProperty Name="name2" ColumnName="name2" />
    </MappingFragment>
  </EntityTypeMapping>
</EntitySetMapping>

I would check these things

  1. Make sure the [Key] on the testTabs class is being set

  2. Make sure you don't have two different instances of ABEntities2 (DbContext) at the same time

looks like the only problem is usage of sequence , since I changed table definition to

CREATE TABLE [dbo].[testTab]
(
    [iden] [bigint] identity(1,1) NOT NULL ,
    [name1] [nchar](10) NULL,
    [name2] [nchar](10) NULL,
    PRIMARY KEY CLUSTERED 
    (
    [iden] ASC
    )
) ON [PRIMARY]
  • so I used identity instead of sequence and recreated model, everything works fine. sequence introduced in sql2012 seems not working with EF6 correctly.

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