ADO.NET Entity Framework and identity columns

前端 未结 10 1475
甜味超标
甜味超标 2020-12-29 18:06

Is the Entity Framework aware of identity columns?

I am using SQL Server 2005 Express Edition and have several tables where the primary key is an identity column. w

相关标签:
10条回答
  • 2020-12-29 18:24

    This is the best answer I've seen. You have to manually edit the storage layer xml to set StoreGeneratedPattern="Identity" on each primary key of type UniqueIdentifier that has the default value set to NewID().

    http://web.archive.org/web/20130728225149/http://leedumond.com/blog/using-a-guid-as-an-entitykey-in-entity-framework-4/

    0 讨论(0)
  • 2020-12-29 18:25

    You should set the identity columns' identity specification so that the (Is Identity) property is set to true. You can do this in your table designer in SSMS. Then you may need to update the entity data model.

    Perhaps that what you mean by saying the "Primary key is an identity column," or perhaps you missed this step.

    0 讨论(0)
  • 2020-12-29 18:26

    I know this post is quite old, but this may help the next person arriving hear via a Google search for "Entitiy Framework" and "Identity".

    It seems that Entity Frameworks does respect server-generated primary keys, as the case would be if the "Identity" property is set. However, the application side model still requires a primary key to be supplied in the CreateYourEntityHere method. The key specified here is discarded upon the SaveChanges() call to the context.

    The page here gives the detailed information regarding this.

    0 讨论(0)
  • 2020-12-29 18:28

    Entity Framework is aware and can handle identity columns.

    Your problem can be maybe not the EF itself but the generated formview of it. Try to delete the input for the identity column from the insert form and let's see what happens.

    0 讨论(0)
  • 2020-12-29 18:29

    Entity framework does not fully understand Identities for some reason. The correct workaround is to set the Setter for that column to Private. This will make any generated UI understand that it should not set the identity value since it is impossible for it to set a private field.

    0 讨论(0)
  • 2020-12-29 18:33

    What worked for me was setting the StoreGeneratedPattern to None, when it was an Identity column. Now it all works consistently. The main problem with this is editing the models is an extreme chore if you have many models.

    0 讨论(0)
提交回复
热议问题