When I create a new model and try to retrieve its ID, it always returns 0.
Why is that? I’m trying it after I add it to the corresponding set and context. As far as I know every time a new model is created, it recalls the DB and assigns a unique ID.
StoreGeneratedPattern value is set to Identify in the Model.edmx file.
It will get number after
context.SaveChanges(). Before it, there is no record in db for your new model object and it is not know id that will be generated on insert.Update:
As example you have two tables: Books and Shelves. Any book can be placed in one of shelves and one shelve can contain many books. Typical one-to-many relationship.
EF generates to you two classes in model:
Class Book:
Class Shelve:
If you want to create a book and place it in existing shelve you should:
If you want to create new shelve and add to it new book then you can use something like next sample: