NHibernate error (Cannot insert duplicate key with unique index)
My Class Client :
public class Client : Entity
{
public Client()
{
ListClientObjectX = new List<ClientObjectX>();
}
public virtual IList<ClientObjectX> ListClientObjectX { get; set; }
...
}
My Class ClientObjectX
public class ClientObjectX: Entity
{
public ClientObjectX()
{
Client = new Client();
ObjectX = new ObjectX();
}
public virtual Client Client { get; set; }
public virtual ObjectX ObjectX { get; set; }
public virtual string Name {get; set;}
...
}
My ClientObjectX table have a unique index with the 2 columns (ClientID and ObjectXID) : idxClientObjectX
The Client mapping (Fluent):
public class ClientMap : ClassMap<Client>
{
public ClientMap()
{
Table("tblClient");
Id(x => x.ID,"ClientID").GeneratedBy.Identity().UnsavedValue(0);
HasMany<ClientObjectX>(x => x.ListClientObjectX)
.Inverse()
开发者_运维百科 .Cascade.AllDeleteOrphan()
.KeyColumns.Add("ClientID");
}
}
So, per example, when I load a Client, that have in ListClientObjectX one object:
var client = new Repository<Client>().Load(2);
And deleted from ListClientObjectX that object:
client.ListClientObjectX.RemoveAt(0);
No save/commit yet. Now I add a object to ListClientObjectX with the same ClientID and ObjectXID:
client.ListClientObjectX.Add(test);
When I Save that, I got a error:
repCliente.SaveOrUpdate(client);
Cannot insert duplicate key row in object 'dbo.tblClientObjectX' with unique index 'idxClientObjectX'. The statement has been terminated.
Why get that error? How Can I fix that?
Thanks
You need to set the ClientObjectX.Client reference to null in addition to removing it from the collection. Removing it from the collection does not make it an orphan so it will not be deleted when the session is flushed.
var objectX = client.ListClientObjectX[0];
client.ListClientObjectX.Remove(objectX);
objectX.Client = null;
It might be a better idea to break the operation up into two transactions; one to delete and another to add an object with the same unique combination. I think you are asking for trouble if you frequently add and remove objects with the same unique combination in a single operation.
You may want to consider a <set>
mapping for this collection instead. Be sure to override Equals() and GetHashCode() on your ListClientObjectX object. This will ensure the uniqueness of the child objects in the collection and will completely avoid the problem of adding duplicates.
精彩评论