Supponiamo di avere un oggetto e vorrei cancellare il suo id e tutte le proprietà di navigazione. È possibile staccarlo? Se è così, allora come posso eseguire questa operazione in EF core?
class Car
{
int Id {get;set;}
int CarTypeId {get;set;}
[ForeignKey(nameof(CarTypeId))]
CarType CarType{get;set;}
...
}
Ho fatto qualcosa di simile di recente. Il normale DbContext non ha un metodo distaccato, quindi ne ho aggiunto uno.
public void Detach<T>(T entity)
where T : class
{
Entry( entity ).State = EntityState.Detached;
}
Successivamente ho creato un metodo per staccare e ripristinare un'entità. L'ho fatto specificamente per un'entità, ma il concetto è così.
public void DetachAndResetKeys(Car entity)
{
// Load references if needed
// Detach
_dbContext.Detach( entity );
// Reset Key. 0 equals not set for int key
entity.Id = 0;
entity.CarType = null;
}
Aggiornamento: per ripristinare le chiavi in fase di scollegamento. Se le chiavi possono essere di diverso tipo, è necessario gestirle anche tu. Qui solo int
public void Detach<T>(T entity)
where T : class
{
Entry( entity ).State = EntityState.Detached;
foreach(var prop in Entry( entity ).Properties) {
if (prop.Metadata.IsKey()) {
prop.CurrentValue = 0;
}
}
}