locked
Set Entity key value RRS feed

  • Question

  • I want to use program keys generated sutomatcaly by my code in the insertion os every entity in my model but i don't want to make it by hand and i still getting in the same error

    the problem is 
    when i try to modify the  entity data model
            partial void OnContextCreated()
            {
                this.ObjectStateManager.ObjectStateManagerChanged += new System.ComponentModel.CollectionChangeEventHandler(ObjectStateManager_ObjectStateManagerChanged);
            }
    
            void ObjectStateManager_ObjectStateManagerChanged(object sender, System.ComponentModel.CollectionChangeEventArgs e)
            {
                if (e.Action == System.ComponentModel.CollectionChangeAction.Add && ((EntityObject)e.Element).EntityState == System.Data.EntityState.Added)
                {
                    var entidade = (ObjectStateEntry)e.Element;
                    
                    var temp = this.CreateEntityKey(entidade.EntityKey.EntitySetName, entidade);
                    EntityKeyMember[] keymember = new EntityKeyMember[1];
                    keymember[0] = new EntityKeyMember(temp.EntityKeyValues[0].Key, 1000/*here a function would put the real key*/);
                    EntityKey chave = new EntityKey();
                    chave.EntityContainerName = entidade.EntityKey.EntityContainerName;
                    chave.EntitySetName = entidade.EntityKey.EntitySetName;
                    chave.EntityKeyValues = keymember;
                    
                    entidade.EntityKey = chave;
                }
            }
    
    whe this code runs it says that i cant modfie the entity data model that it can only be set when it is null
    any one got a workaround
    Thursday, May 28, 2009 7:19 PM

Answers

  • Gabriel,

    You cannot set the EntityKey property of an entity that is in the Added state, which is always the case when you get the "Added" action of the ObjectStateManager event. Let me give you some more context and then a work around:

    Entities that are in the "Added" state (newly created, and not yet saved) have what is called a temporary EntityKey. This EntityKey has an EntitySet, but no key values because the entity is still Added. The key cannot become a real EntityKey (an EntityKey with values) until you save the Entity.

    What you can do, and here is the work around I think you should use, is to assign your generated value to the primary keys of the entity, which looks to be essentially what you are doing above.  For example, set enitade.ID = 1000 /* here a function...*/. When you call SaveChanges (or AcceptAllChanges), the EntityKey will automatically pick up there values from the primary keys, and we'll replace all references to that key with the values.

    Jeff



    This posting is provided "AS IS" with no warranties, and confers no rights.
    Monday, June 1, 2009 3:16 PM