Let's assume that I have an object and I would like to clear its id and all navigation properties. Is is possible by detach? If so, then how can I perform this operation in EF core?
class Car
{
int Id {get;set;}
int CarTypeId {get;set;}
[ForeignKey(nameof(CarTypeId))]
CarType CarType{get;set;}
...
}
I did something like this recently. The normal DbContext does not have a detached method, so I added one.
public void Detach<T>(T entity)
where T : class
{
Entry( entity ).State = EntityState.Detached;
}
Next I made a method to detach and reset an entity. I made it specifically for one entity, but concept is like this.
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;
}
Update: To reset keys on detach. If keys can be different types, need to handle that as well. Here only 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;
}
}
}