Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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,
cheers
Andy
Posted
Comments
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 ;)

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.

C#
/// <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.
        if(success)
          return entity;
    } catch (OptimisticConcurrencyException concurrencyException) {
        entityRepository.Dispose();
        throw concurrencyException;
    } catch (Exception addRecordException) {
        entityRepository.Dispose();
        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.
C#
/// <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);
    this.objectContext.SaveChanges();
    return true;
}
 
Share this answer
 
v4
Comments
Espen Harlinn 10-Feb-12 12:50pm    
5'ed!
Wonde Tadesse 10-Feb-12 12:56pm    
Thanks
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.
...am I missing something here?
cheers
Andy
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 ;)
cheers
Andy
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.
 
Share this answer
 
Comments
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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900