We're using C# with EF 6 Code first approach and have got a bunch of entity types. Is it possible to disable inserts & updates for only one single entity type and still use EF 6 for delete/select operations for that specific entity type?
I'm currently overriding the SaveChanges method in my DbContext class and checking whether specific entity type is present in the changes with insert/update and then manually doing inserts/updates to the database using ADO.NET and re-setting the state of all the instances of that entity type to "Unchanged" and then calling the base.SaveChanges().
Even though now the new values are updated to the database (through ADO.NET), they aren't getting reflected back in the entities, when I try to use those entities again and are being reset with the original old values, but not the one's which they were modified to and saved to the database.
I still have to call the base.SaveChanges() because the user might have performed various operations, which would have effected other entity types and they should still be updated to the db through the EF.
Is there a way that I can still persist the changed values in the entity instances even though I manually update them to the db.
public override int SaveChanges()
{
// Save to database using Ado.Net
this.SaveEmployeeEntitiesIfAny();
// Have to call this so that other entity types with their changes
// can be persisted to the database through EF.
return base.SaveChanges();
}
private void SaveEmployeeEntitiesIfAny()
{
// Retrieve the list of Added or Updated Employee Type Entities
var employeeEntities = this.ChangeTracker
.Entries<EmployeeEntity>()
.Where(x => x.State == EntityState.Modified || x.State == EntityState.Added);
// Insert them to the database through Ado.Net
// Manually reset the state to Unchanged so that base.SaveChanges() won't pick it
foreach (var entry in dbEntityEntries)
{
this.Entry(entry.Entity).State = EntityState.Unchanged;
}
}
A partial answer accepted by the OP in the comment below the question is to set the entity state to detached rather than unchanged.
Detached would make EF forget it ever touched the entity and force reload it when it's needed the next time.
While this solution work, there are some performance considerations, not touched in the original answer but mentioned in comments.