Reference testing new entities on IndexOf,

Posts   
 
    
craigmain
User
Posts: 22
Joined: 17-Apr-2005
# Posted on: 23-Apr-2005 10:28:49   

Hi,

I have a problem, I have added a new entity to a collection, and assigned it a GUID (I am using these as primary key values in this case).

                    foreach (IEntityField2 field in targetEntity.PrimaryKeyFields)
                        targetEntity.Fields[field.Name].CurrentValue = entity.Fields[field.Name].CurrentValue;
                    targetEntity.IsNew = false;
                    int index = n.IndexOf(targetEntity);

I am trying to find the entity based on its' primary key value. I cannot seem to do this as the IndexOf method compares references instread of key values.

<snippit from EntityBase2>

            // new entities are always different. If one of the two (this, or passed in object) is new, they have to be tested using reference testing.
            // if that fails, they're not the same. New entities can't be compared using field values
            if(this.IsNew || passedIn.IsNew) {
                // one or both is new, use instance compare.
                bool ba = this.IsNew;
                bool bb = passedIn.IsNew;
                return (this==passedIn);
            }

My problem is: How do I search for an entity based on its key value (or any other value for that matter) when it may be a new entity or it may not. Does a simple search of this nature exist?

Regards Craig

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39933
Joined: 17-Aug-2003
# Posted on: 23-Apr-2005 11:36:59   

CollectionBase.IndexOf(), which is the routine you're using, does a linear search, using Equals. As identity columns don't have a value (i.e.: 0) when they're new, for new entities, an instance compare is performed.

As IndexOf() by default (the .NET implementation) performs a linear search, you can also do that yourself: foreach(FooEntity f in foos) { if(f.ThePK==_value) { // found it } }

Frans Bouma | Lead developer LLBLGen Pro