2

我有下一个问题。我的代码上下文+模型:

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,并且我的存储库类中有一些逻辑可以将常规删除处理为更新,更改EntityStateModified而不是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实体吗?是解决我的问题吗?

备注:相关实体作为投影加载到根对象,正如 Julie 在“可能无法按预期工作的场景”段落中所说的那样,可能会对已经被上下文跟踪的实体产生问题。

4

1 回答 1

0

代码:

public override int SaveChanges()
{
    var result = base.SaveChanges();
    // AfterSave code
    var isDeletedEntities = EfContext.ChangeTracker
        .Entries()  
        .Select(dbE => new {  
             DBEntity = dbE,  
             BaseObject = (dbE.Entity as IBaseObject)})  
        .Where(dbe => dbe.BaseObject.IsDeleted);  

    foreach (var isDeletedEntity in isDeletedEntities)  
    {  
        isDeletedEntity.DBEntity.State = EntityState.Detached;  
    }
}
于 2012-11-04T08:42:38.423 回答