2
我有下一個問題。我的代碼上下文+模式:EF代碼第一+刪除標記爲已修改的孤兒(IsDeleted = 1)
public class MediaPlanContext : DbContext
{
public MediaPlanContext() : base(lazyLoading:false) {}
public DbSet<MediaPlan> MediaPlan { get; set; }
public DbSet<MovieType> MovieType { get; set; }
public DbSet<MediaPlanItem> MediaPlanItems { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder
.Entity<MediaPlanItem>()
.HasKey(mpi => new {mpi.Id, mpi.MediaPlanId});
modelBuilder
.Entity<MediaPlanItem>()
.Property(mpi => mpi.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder
.Entity<MediaPlan>()
.HasMany(mp => mp.MediaPlanItems)
.WithRequired()
.HasForeignKey(mpi => mpi.MediaPlanId)
.WillCascadeOnDelete();
}
}
public class MediaPlan : IBaseObject
{
public virtual ICollection<MediaPlanItem> MediaPlanItems { get; set; }
}
public class MediaPlanItem : IBaseObject
{
public int MediaPlanId {get;set;}
public MediaPlan MediaPlan {get;set;}
}
public interface IBaseObject
{
public int Id {get;}
public DateTime DateCreated {get;}
public DateTime DateModified {get;set;}
}
而且我用的資源庫和我對象(IBaseObject-s
)和根對象MediaPlan處理。 當我的數據庫中的對象將被刪除時,我將實體(記錄)標記爲IsDeleted = 1
,並且我的存儲庫類中有一些邏輯處理常規刪除作爲更新,將EntityState
更改爲Modified
而不是Deleted
。
問題與下面的代碼:
var rep = new MediaPlanRepository(new MediaPlanContext());
var withItems = rep.GetWithMediaPlanItems();
var m1 = withItems.First();
var mpi1 = m1.MediaPlanItems.First();
m1.MediaPlanItems.Remove(mpi1); // 6 items before remove
// 5 items after remove
rep.SaveChanges();
// 6 items after save changes :(
問:我能處理當下的SaveChanges發生和分離我IsDeleted = 1
實體後?是解決我的問題嗎?
備註:作爲projection加載到根對象的相關實體,以及Julie在段落'情景如果這可能無法按預期工作'的情況下可能會產生已經被上下文跟蹤的實體的問題。
我的DbContext overrided的SaveChanges並插入我保存後的邏輯分離我修改的對象(如標註請將isDeleted = 1),它的工作,但我認爲這不是很好的解決方案。 –