I have a class Ricevuta which holds a collection of VoceRicevuta:
public partial class Ricevuta : GestPreBaseBusinessObject
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public long Id { get; set; }
...
[InverseProperty("Ricevuta")]
public virtual ObservableListSource<VoceRicevuta> Voci { get; set; }
}
A VoceRicevuta holds optional references to different classes, let's consider only the one to Prestazione class:
public partial class VoceRicevuta
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public long Id { get; set; }
public long IdRicevuta { get; set; }
....
public virtual Prestazione Prestazione { get; set; }
[ForeignKey("IdRicevuta")]
public virtual Ricevuta Ricevuta { get; set; }
}
Ok, the problem now is the following: I create an Instance of Prestazione (let's call it PreInst) and save it to the database. I detach PreInst from that DbContext instance. Then, I pass PreInst to another form (another DbContext - I must do that), create a Ricevuta, a VoceRicevuta (added to the just created Ricevuta) and assign PreInst to VoceRicevuta Prestazione property. I also made some changes to PreInst. Now I want to save to database the new Ricevuta, the new VoceRicevuta, its relation to PreInst and the changes to PreInst. I run the following:
db.UpdateGraph(Ricevuta, map =>
map.OwnedCollection(ric => ric.Voci,
with => with
.OwnedEntity(voce => voce.Prestazione)
));
But i get the error:
"Violation of PRIMARY KEY constraint 'PK_dbo.Prestazioni'. Cannot insert duplicate key in object 'dbo.Prestazioni'. Vlue of duplicate key: (12115)"
I can't understand why! Isn't Graph diff purpose cheching if any part of the graph is already present in Db and behave consquently?
I tried to attach PreInst to DbContext before running the code above and saving. Now the error thrown is:
Multiplicity constraint violated. The role 'Prestazione_VoceRicevuta_Source' of the relationship 'Gestione_Prestazioni.Prestazione_VoceRicevuta' has multiplicity 1 or 0..1.
Any hint?