How can I detach an entity from data graph using Entity Framework Core?

.net-core c# entity-framework-core

Question

Lets say I have an entity Vehicle which references another entity Type through TypeId. I want to update Vehicle using Entity Framework but I don't want to update TypeId (or Type).

The problem is that Entity Framework wants to update the whole graph and the result is that the properties of the Type entity is overwritten with empty values when updating Vehicle.

I guess I could fetch the Type entity from the data source before updating, but it seems unnecessary to make two extra calls (read and save) to the database to update an entity not needed to be updated.

I would much rather detach the Vehicle entity from the graph and only update only this entity. How can I do this?

Edit:

Here is some code to make the question clearer:

public async Task Update(Vehicle entity)
{
    var dataEntity = mapper.Map<VehicleDataEntity>(entity);
    await repository.Update(entity.Id, dataEntity);
}

As you can see the data entity is instantiated during mapping (using Automappar).

Updating is done in a simple generic repository:

public async Task Update(Guid id, TEntity entity)
{
    dbContext.Set<TEntity>().Update(entity);
    await dbContext.SaveChangesAsync();
}

Here is the data model:

public class VihecleDataEntity : IEntity
{
    [Key]
    public Guid Id { get; set; }
    public string Description { get; set; }
    public VihecleTypeEntity Type { get; set; }
}

public class VihecleTypeEntity: IEntity
{
    [Key]
    public Guid Id { get; set; }
    public string Description { get; set; }
}
1
0
9/20/2019 8:27:07 AM

Popular Answer

If you want to update only VehicleDataEntity properties, you can set VehicleDataEntity.Type property to null. That wouldn't delete the relation but, would prevent EF from updating properties of the related entity.

0
9/20/2019 5:11:39 PM


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