问题
In order to execute some actions for all entities deletions I'm trying to handle it like this:
public override int SaveChanges()
{
var deletedEntities = ChangeTracker.Entries()
.Where(p => p.State == EntityState.Deleted).ToList();
foreach (var deletedEntity in deletedEntities)
{
//((SampleEntity)deletedEntity.Entity).SuperCollection.Count();
}
return base.SaveChanges();
}
I need to handle some entity collections during the deletion process based on the entity collection properties count, but it always returns 0, even when the collection has many items.
((SampleEntity)deletedEntity.Entity).SuperCollection.Count();
Any idea why my collections are always 0 at this point?
My models are properly lazy loading coded as following and my collections works very well out of the SaveChanges()
public partial class SampleEntity
{
public int MyId { get; set; }
public string Description { get; set; }
public SampleEntity()
{
this.SuperCollection = new HashSet<UnitCompany>();
}
public virtual ICollection<AnyOtherEntity> SuperCollection { get; set; }
}
Best regards
回答1:
Call DetectChanges before:
public override int SaveChanges()
{
ChangeTracker.DetectChanges();
//...
return base.SaveChanges();
}
Otherwise, changes will be detected only in base.SaveChanges() method.
EF will drop all references to related objects for deleted entites. If you need to save this relations, you can save them in local field:
class UnitCompany
{
private SampleEntity _entity;
private SampleEntity _prevEntity;
publc SampleEntity Entity
{
get { return _entity; }
set
{
if (value != null)
{
_prevEntity = value;
}
_entity = value;
}
}
}
_prevEntity keeps link to related object and you can get it in SaveChanges
来源:https://stackoverflow.com/questions/45067138/ef-changetracker-entity-collections-count-always-0