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
It is pretty easy. If you are using DB generated Ids (like
IDENTITY
in MS SQL) you just need to add entity toObjectSet
andSaveChanges
on relatedObjectContext
.Id
will be automatically filled for you:Entity framework by default follows each
INSERT
withSELECT SCOPE_IDENTITY()
when auto-generatedId
s are used.You can get ID only after saving, instead you can create a new Guid and assign before saving.
I had been using Ladislav Mrnka's answer to successfully retrieve Ids when using the Entity Framework however I am posting here because I had been miss-using it (i.e. using it where it wasn't required) and thought I would post my findings here in-case people are looking to "solve" the problem I had.
Consider an Order object that has foreign key relationship with Customer. When I added a new customer and a new order at the same time I was doing something like this;
However in my case this was not required because I had a foreign key relationship between customer.Id and order.CustomerId
All I had to do was this;
Now when I save the changes the id that is generated for customer is also added to order. I've no need for the additional steps
I'm aware this doesn't answer the original question but thought it might help developers who are new to EF from over-using the top-voted answer for something that may not be required.
I come across a situation where i need to insert the data in the database & simultaneously require the primary id using entity framework. Solution :
Please refer this link.
http://www.ladislavmrnka.com/2011/03/the-bug-in-storegeneratedpattern-fixed-in-vs-2010-sp1/
You have to set the property of StoreGeneratedPattern to identity and then try your own code.
Or else you can also use this.
You need to reload the entity after savechanges. Because it has been altered by a database trigger which cannot be tracked by EF. SO we need to reload the entity again from the DB,
Then
Look at @jayantha answer in below question:
How can I get Id of inserted entity in Entity framework when using defaultValue?
Looking @christian answer in below question may help too:
Entity Framework Refresh context?