views:

93

answers:

4

Hi, I'm learning Entity Framework under VC# 2010. I have created a simple table for learning purposes, one of the fields is "id" type integer, indentity set to true. I've generated Entity Data Model from that table and connected it with dataGridView. The problem is that it doesn't auto increment - each inserted row wants to be id=0 (which is impossible of course, since id must be unique)

what am I doing wrong? how should I configure EF or the SQL db itself?

thanks

A: 

Be sure you're saving your Entities back to the database before you try to read the auto-incremented Id value.

Your Id won't be set by auto-increment until the first time it is actually saved to the database.

Justin Niessner
the problem is, that while calling SaveChanges (after adding multiple rows) it throws an exception about duplicated primary key...
vic
@vic - Interesting. Are you sure it's failing on the insert for the Auto-Incremented key table?
Justin Niessner
A: 

Yes. LINQ to SQL behaves the same way. The id will not be set until it is saved to the database. Until you do, all the ids will be zero (as you've already seen).

Vinny Brown
A: 

The identity isn't set and incremented just by adding to the entity set... The entity isn't actually saved to the db until you call context.SaveChanges()...

db.AddToUserSet(user);//Added to EF entity collection
db.SaveChanges();//INSERT executed in db, Identity set and incremented.
DShultz
the problem is, that while calling SaveChanges (after adding multiple rows) it throws an exception about duplicated primary key...
vic
+1  A: 

Check in your EDMX model, that the autoincrement field's StoreGeneratedPattern attribute is set to "Identity". In this way, EF knows that the autonumbers are handled by the DB.

Here this is explained better: http://stackoverflow.com/questions/3011764/autonumber-with-entity-framework/3038265#3038265

cepriego
Yeah generally from the VS2010 generated pieces you will have to set the StoreGenerated Value in the top large block of xml. You are getting multiple primary keys because unless you change that, EF is generating the ID for you, as 0.
Rangoric