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; }
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.