I have a problem with Entity Framework in Asp.net. I want to get the Id value whenever I add an object to database. How can I do this?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
The object you're saving should have a correct
Id
after propagating changes into database.All answers are very well suited for their own scenarios, what i did different is that i assigned the int PK directly from object (TEntity) that Add() returned to an int variable like this;
so instead of creating an entire new object, you just take what you want :)
EDIT For Mr. @GertArnold :
This will work.
When you use EF 6.x code first
and initialize a database table, it will put a
inside the table properties under the header Default Value or Binding, allowing the ID to be populated as it is inserted.
The problem is if you create a table and add the
part later, future update-databases won't add back the (newsequentialid())
To fix the proper way is to wipe migration, delete database and re-migrate... or you can just add (newsequentialid()) into the table designer.
There are two strategies:
Use Database-generated
ID
(int
orGUID
)Cons:
You should perform
SaveChanges()
to get theID
for just saved entities.Pros:
Can use
int
identity.Use client generated
ID
- GUID only.Pros: Minification of
SaveChanges
operations. Able to insert a big graph of new objects per one operation.Cons:
Allowed only for
GUID