Al Lelopath Al Lelopath - 2 years ago 133
C# Question

Duplicate key value error on Merge

I get this error on the code below. I don't understand how it can give a duplicate key value error. The key does indeed exist in the database but the code specifies

Merge
. Also, when I first create the entity and save it to the db, all is well, the error occurs only on saves after that. If I add a line to do a
Session.Refresh
before the
Session.Merge
(which restores the entity to the values in the db) the error does not occur. That defeats the point of making any changes, but it shows that it doesn't like changes to
entity
. I've tried playing with different values for
cascade
, but makes no difference. The table has 2 columns
ProjectId
and
FeatureId
, both are Primary Keys. What gives?

It appears the first part of a merge consists of a SQL Delete and the Delete is failing.


Could not execute batch command.[SQL: SQL not available]
Cystem.Data.SqlClient.SqlException (0x80131904): Violation of PRIMARY
KEY constraint 'PK_tblProjectFeature'. Cannot insert duplicate key in
object 'dbo.tblProjectFeature'. The duplicate key value is (179,
5844). Violation of PRIMARY KEY constraint 'PK_tblProjectFeature'.
Cannot insert duplicate key in object 'dbo.tblProjectFeature'. The
duplicate key value is (179, 5844).


public virtual T Merge (T entity)
{
using (ITransaction transaction = this.Session.BeginTransaction())
{
try
{
Session.Merge(entity);
transaction.Commit();
}
catch (System.Exception ex)
{
transaction.Rollback();
throw ex;
}
}
return entity;
}


hbm.xml

<bag name="Projects" table="tblProjectFeature" inverse="false" lazy="true" cascade="none">
<key>
<column name="FeatureId" sql-type="int" not-null="true" />
</key>
<many-to-many class="BusinessEntities.Project, Infrastructure.Interface">
<column name="ProjectId" sql-type="int" not-null="true" />
</many-to-many>
</bag>

Answer Source

Change the mapping file to inverse to true.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download