49

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. when I use these tables to create an entity model and use the model in conjunction with an entity datasource bond to a formview in order to create a new entity I am asked to enter a value for the identity column. Is there a way to make the framework not ask for values for identity columns?

abatishchev
  • 98,240
  • 88
  • 296
  • 433

10 Answers10

66

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.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
biozinc
  • 4,629
  • 2
  • 25
  • 28
5

If you are using Entity Framework 5, you can use the following attribute.

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
Siva
  • 543
  • 4
  • 6
4

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.

YeahStu
  • 4,032
  • 5
  • 48
  • 69
3

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/

enricoide
  • 83
  • 1
  • 9
John West
  • 41
  • 2
  • After reading this bit of advice, I found a missing identity had been added, but EF needed to drop and refresh the object in the entity data model to fix everything. – goosemanjack May 30 '12 at 04:13
2

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.

Biri
  • 7,101
  • 7
  • 38
  • 52
2

If all else fails before you rip out your hair - try deleting your EntityModel and re-importing from SQL Server. If you've been tweaking the keys and relationships and relying on the 'update model from database' function it's still a bit buggy in the RC version I've found - a fresh import may help.

scotta
  • 244
  • 1
  • 4
  • This still holds true 7 years later. Refresh wasn't picking up my Key changes. Creating a fresh model solved the issue. – mr_plum Aug 28 '15 at 18:13
2

In C# you can do something like this to make it aware:

In your FooConfiguration.cs : EntityTypeConfiguration<Foo>:

this.Property(x => x.foo).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

Then to use it, just be sure to insert the item into the context and call context.SaveChanges() before using x.foo to get the updated auto-incremented value. Otherwise x.foo will just be 0 or null.

aladd04
  • 439
  • 5
  • 14
1

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.

  • In this case, you wont be able to edit the entity via the key, since the value will be 0 for the updated object and you wont be able to save the upadted changes as you cant find the object in the collection via the key. (this case is for MVC) – Chinjoo Jul 08 '10 at 04:05
0

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.

Community
  • 1
  • 1
Nick
  • 1,174
  • 11
  • 20
0

I cannot believe it. Intellisensing ItemCollection yield the single item with ID = 0 after SaveChanges.

            Dim ItemCollection = From d In action.Parameter
            Select New STOCK_TYPE With {
                        .Code = d.ParamValue.<Code>.Value,
                        .GeneralUseID = d.ParamValue.<GeneralUse>.Value,
            }


            GtexCtx.STOCK_TYPE.AddObject( ItemCollection.FirstOrDefault)
            GtexCtx.SaveChanges()

No matter what I do. After 8 hours including deleting my model, 35 times building and rebuilding, experimenting and editing the XML of EDMX and now almost coming to deleting my whole SQL Server database. At the 36th compile, this dumbfounding solution worked

            Dim abc = ItemCollection.FirstOrDefault
            GtexCtx.STOCK_TYPE.AddObject(abc)
            GtexCtx.SaveChanges()

abc.ID yield 41 (the identity i needed)

EDIT: Here's a simple code for thought for looping AddObject and still get ID

Dim listOfST As List(Of STOCK_TYPE) = ItemCollection.ToList()
      For Each q As STOCK_TYPE In listOfST 
         GtexCtx.STOCK_TYPE.AddObject(q)
      Next
 GtexCtx.SaveChanges()

...more code for inter-relationship tables

Try Intellisence listOfST after SaveChanges and you will find updated ID. Maybe there's better way but the concept is there