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
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.
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
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.
If you are using Entity Framework 5, you can use the following attribute.
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]