EF Core - how to clear object's id and its navigation properties

asp.net-core c# entity-framework-core

Question

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;}

     ...
}
1
0
3/2/2017 7:51:53 AM

Accepted Answer

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;
        }
    }
}
1
3/2/2017 8:17:12 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow