Search code examples
entity-frameworkconstraintsguid

Entity Frmwk pb: search for 'added' entities in current context


I'm using guids as PK for my entities. As EF doesn't support the newid() SQL statement, I force a Guid.NewGuid() in my creation methods.

Here is my problem : I've a table with a clustered unique constraint (2 strings, not PK).

I'm running some code in the same EF context which perfoms operations and adds/links entities, etc.

Is it possible to search for an entity in 'Added' state in my context ? ; that is to say which is in my context, but not yet inserted in my DB.

To avoid the raising of the SQL unique constraint, I have to know if the entity is already 'queued' in the context, and to re-use it instead of creating a new Guid (... and a different entity! :( )


Solution

  • this post saved me :) :

    Link

    var stateEntries = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EtityState.Modified | EntityState.Unchanged);  
        var roleEntityEntries = stateEntries.Select(s => s.Entity).OfType<Role>();  
        roleEntity = roleEntityEntries.FirstOrDefault(r => r.RoleName.Trim().ToLower() == roleName.Trim().ToLower());  
        if (roleEntity == null)  
        {  
            return new Role { RoleName = roleName };  
        }