2

I have a problem with Entity Framework in Asp.net. I want to get the Id value whenever I add an object to database without executing SaveChanges(). How can I do this?

  • Just add the object to the database without SaveChanges(). Thing is, the object will still be in the database. You cannot add it and not add it. If you want to be able to revert the changes, consider looking at _transactions_. – oerkelens Dec 08 '17 at 12:32
  • `I want to get the Id value whenever I add an object to database without executing SaveChanges().` Why do you want to do this? What is your **underlying** problem? – mjwills Dec 08 '17 at 12:40
  • You probably want to know the ID to set a foreign key, right? Well, that's hardly ever necessary if you set navigation properties (object references) instead of IDs. – Gert Arnold Dec 08 '17 at 16:05

1 Answers1

3

If you use a Sequence to generate your key values instead of an IDENTITY column, you can fetch the key value before inserting into the database.

EF Core supports this natively Sequences, and you can do this in EF6 with a little custom SQL.

David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67