我需要实现软删除行为。为此,我如下重写DbContext的SaveChanges()方法:
public override int SaveChanges()
{
var deletableEntries = ChangeTracker.Entries<IDeletable>().Where(e => e.State == EntityState.Deleted);
foreach (var entry in deletableEntries)
{
entry.State = EntityState.Modified;
entry.Entity.Deleted = true;
}
return base.SaveChanges();
}
但是,当从DbSet中删除实体时,其外键将重置为null:
var context = new MyContext();
var entity = context.Citizens.FirstOrDefault(e => e.CityCode == "001");
if (entity != null)
{
context.Citizens.Remove(entity); // After that, entity.CityCode becomes Null
context.SaveChanges();
}
为什么会发生这种情况以及如何预防呢?
型号:
public class City
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Key]
public string Code { get; set; }
public string Name { get; set; }
public virtual ICollection<Citizen> Citizens { get; set; }
}
public class Citizen: IDeletable
{
public int Id { get; set; }
[Required]
public string CityCode { get; set; }
public virtual City City { get; set; }
public string Name { get; set; }
public bool Deleted { get; set; }
}
模型配置:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Citizen>()
.HasRequired(e => e.City)
.WithMany(e => e.Citizens)
.HasForeignKey(e => e.CityCode)
.WillCascadeOnDelete(false);
}
实体框架版本:6.1.3