For an application using Code First EF 5 beta I have:
public class ParentObject
{
public int Id {get; set;}
public virtual List Ch
Want to share another .net ef core solution that worked for me, may be somebody will find it usefull.
I had a child table with two foreign keys (either or), so the accepted solution didn't work for me. Based on the answer by Marcos Dimitrio I came up with the following:
In my custom DbContext:
public override async Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
var modifiedEntities = this.ChangeTracker.Entries().Where(c => c.State == EntityState.Modified);
foreach (var entityEntry in modifiedEntities)
{
if (entityEntry.Entity is ChildObject)
{
var fkProperty = entityEntry.Property(nameof(ChildObject.ParentObjectId));
if (fkProperty.IsModified && fkProperty.CurrentValue == null && fkProperty.OriginalValue != null)
{
// Checked if FK was set to NULL
entityEntry.State = EntityState.Deleted;
}
}
}
return await base.SaveChangesAsync(cancellationToken);
}