Click here to Skip to main content
13,097,230 members (63,233 online)
Rate this:
Please Sign up or sign in to vote.
See more:
Hi all,
I was wondering if there is any way to find out what identity value an EntityObject will get in the SavingChanges event.

any help is kindly appreciated,
Posted 10-Feb-12 3:45am
Christian Graus 10-Feb-12 9:57am
Do you mean if a new object is added to the database ?
hoernchenmeister 10-Feb-12 10:08am
I have added a partial OnContextCreated to my context that registers the SavingChanges event.
I am doing this in order to audit the changes that have been made to the context.
Then I save the changed column values together with the DataRowState and the id for the entry.
This works fine for Modified/Deleted entries, but for Added entries I can not store the id (because it is not created at this point).
I could store 0, but that doesn't help finding the added entry later in the database.

So now I am searching for a way to get the real id of the entry that will be added.
I hope I could explain what I want to do ;)
darkDercane 10-Feb-12 11:42am
Do you mean Persist???
cos the context of the repository it have a persist method, when you call that method automatically your object is actualized with the lastest ID(only if that field is Identity in your DB) :)
hoernchenmeister 13-Feb-12 4:40am
Thanks for your comment.
I googled for a while but I couldn't find a "persist" method related to the ObjectContext. I found out about the repository pattern though.
Would you mind to point me into the right direction on where to search?
That'll be great ;)
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

As far as you are using the latest version for EF(4.0,4.1), there is no problem getting the last inserted entity object identity value. Note The identity column value will be returned only after the inserted statement committed successfully.

1. Insert the Entity Object.
2. Save the Entity Object using database context object SaveChanges() method
3. Don't dispose the database context object.
4. Return the Entity Object from your method.

/// <summary>
/// Add Type Customer entity to the repository
/// </summary>
/// <typeparam name="Customer">Type Customer entity to be added</typeparam>
/// <param name="entity">Customer  entity to be added and returned</param>
/// <returns>Type Customer  entity object</returns>
/// <remarks></remarks>
public Customer  AddRecord<Customer>(Customer entity)
    try {
        bool success = entityRepository.AddRecord<Customer>(entity); // Note : The repository must not dispose the database context in order to get the last identity value of the Entity Object.
          return entity;
    } catch (OptimisticConcurrencyException concurrencyException) {
        throw concurrencyException;
    } catch (Exception addRecordException) {
        throw addRecordException;
    return null;

The AddRecord method from the repository looks something like this. Note. It just code fragment, there are lots of methods that should be contained in the repository.
/// <summary>
/// Add entity to the repository
/// </summary>
/// <typeparam name="E">An Entity type object type which is going to be added</typeparam>
/// <param name="entity">The entity to be added</param>
/// <returns>True/False</returns>
/// <remarks></remarks>
public bool AddRecord<E>(E entity)
    this.objectContext.AddObject(GetBaseType(typeof(E)).Name.ToString(), entity);
    return true;
Espen Harlinn 10-Feb-12 12:50pm
Wonde Tadesse 10-Feb-12 12:56pm
hoernchenmeister 13-Feb-12 4:34am
Thanks for your help.
Ok, I understand that there is a way to check for the last inserted identity value. The problem is that I currently have no way to check anything after the insert is completed.
The point from where I have to try this is the SavingChanges event of the context.
As mentioned, I do some kind of auditing so I implemented an interface for the context (and all contexts that need the auditing options) that helps me and my colleagues to easily add this capabilities.
So now the context fires its SavingChanges event. All I got is the context and the entities and their changes (added/modified/deleted).
As far as I know I can not attach anything to the context/entity that enables me to execute any code after the insert is done. I missing something here?
Wonde Tadesse 13-Feb-12 15:39pm
Answer updated.
hoernchenmeister 17-Feb-12 3:02am
Thanks Wonde Tadesse for this nice explanation.
It helped me get the picture and inspired me to find a solution to my problem.
I finally decided to use a wrapper for auditing purposes instead of extending the EntityObject. Tha gives me the opportunity to track EntityObjects and get the id after they have been inserted.
Thanks for your help, it is definitely worth a five ;)
Wonde Tadesse 17-Feb-12 10:53am
You're welcome
Member 11597752 28-Apr-15 11:51am
would you mind showing how you did it? I am looking for something similar. The code I have can capture/give me the identity of last entry, but the problem is if there were multiple rows added, it only gives me id for the last row - hence incomplete auditing.
VJ Reddy 23-Apr-12 19:31pm
Wonde Tadesse 24-Apr-12 19:31pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

Identity values don't exist until the row is actually inserted into the table. I've not used EF myself but if it follows the Microsoft standards then 'SavingChanges' will be fired before that happens, to allow you to validate or modify the object before it actually gets saved. That means that in this event, there won't yet be a row created in the database and therefore it is logically impossible to get the identity value (since the database engine didn't make one yet).

You need to save a placeholder, and catch the event issued when a row is successfully saved ('SavedChanges' at a guess). At that point you should be able to determine the value that was actually assigned.
hoernchenmeister 13-Feb-12 4:28am
Thanks for your help.
I guess you pointed out the problem pretty nicely. There is no option to get the id before the values are actually written to the database, which of course makes sense.
Problem is that there is no such event like "SavedChanges", only "SavingChanges" which is the place where I am currently trying to attach anything that might enable me to check the id later.
I also wasn't able to attach anything to the entity that will be saved when the SavingChanges event is fired so I can not check the id after the insert is completed (as far as I know)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web01 | 2.8.170813.1 | Last Updated 13 Feb 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100