Violation of PRIMARY KEY constraint

Posts   
 
    
jzhang28
User
Posts: 2
Joined: 07-Apr-2006
# Posted on: 03-Apr-2007 00:28:37   

An error I encountered makes me confuse. The two tables are gorder, and gordergroup which are applied the cascade insert and update without delete cascade. I want to fetch the ordergroup and update value of some field. I got error when I save. What's the problem?

My code: DataAccessAdapter adapter = new DataAccessAdapter(); GOrderEntity go = new GOrderEntity("2695cc08"); //orderid EntityCollection ec = go.GorderGroup;

IPrefetchPath2 path = ...

adapter.FetchEntityCollection(ec,null,0,null,path);

string prodcode = "UPS";

foreach(GOrderGroupEntity gog in ec) { gog.IsNew=false; gog.ShipMethod=prodcode; adapter.SaveEntity(gog); }

Error messages: An exception was caught during the execution of an action query: Violation of PRIMARY KEY constraint 'PK_gOrder'. Cannot insert duplicate key in object 'gOrder'. The statement has been terminated.. Check InnerException, QueryExecuted and Parameters of this exception to examine the cause of this exception.

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 03-Apr-2007 06:19:08   
My code:
DataAccessAdapter adapter = new DataAccessAdapter();
GOrderEntity go = new GOrderEntity("2695cc08"); //orderid
EntityCollection ec = go.GorderGroup;

Where you fetch go entity?

foreach(GOrderGroupEntity gog in ec)
{   
    gog.IsNew=false; gog.ShipMethod=prodcode;
    adapter.SaveEntity(gog);
}

I think isn't necessary gog.IsNew = false (the entities are fresh fetched). And even adater.SaveEntity as you can Save the entire collection at once.

I suggest you the next rewrite:

DataAccessAdapter adapter = new DataAccessAdapter();

GOrderEntity go = new GOrderEntity("2695cc08"); //orderid
IPrefetchPath2 path = new PrefetchPath2((int) EntityType.GOrderEntity);
path.Add(GOrderEntity.PrefetchPathGorderGroup);
path.Add(...)

// retrieve the graph
adapter.FetchEntity(go, path);
                        
string prodcode = "UPS";    
    
// update the collection
foreach(GOrderGroupEntity gog in go.GorderGroup)
{   
    gog.ShipMethod=prodcode;    
}

// save recursive without refetch
adapter.SaveEntity(go, false, true);

And if you only want to update the prodcode, you can use this:

DataAccessAdapter adapter = new DataAccessAdapter();

// filter to update
IRelationPredicateBucket filter = new RelationPredicateBucket();
filter.Add(GOrderFields.IdGOrder == "2695cc08");

// new values to update
GorderGroupEntity newValues = new GorderGroupEntity();
newValues.ShipMethod = "UPS";

// make the update
adapter.UpdateEntitiesDirectly(newValues, filter);
David Elizondo | LLBLGen Support Team
jzhang28
User
Posts: 2
Joined: 07-Apr-2006
# Posted on: 03-Apr-2007 20:19:08   

Your suggestion is perfect. Great Thanks.