Breeze Server Side:更改EntityState以启用软删除

时间:2013-05-23 19:27:58

标签: breeze

我想在我的数据库中进行软删除。我通过将IsDeleted值设置为true来标记删除来处理对数据库的删除。相应地,我希望Breeze查询排除设置了IsDeleted标志的行。

我更喜欢在服务器端而不是在客户端上执行此操作。

我可以拦截自定义Breeze EFContextProvider中的删除并设置IsDeleted属性。我想设置entityInfo.EntityState = EntityState.Modified并继续更新。但是,似乎entityInfo.EntityState是只读的。

还有其他方法可以实现这个目标吗?

4 个答案:

答案 0 :(得分:1)

我想我可能已经找到了一个使用Entity Framework做这个服务器端的好方法。

您需要创建一个存储过程,为表中的特定行设置IsDeleted为true。

然后在edmx文件中,转到实体的Mapping Details,然后选择Map Entity to Functions。点击并提供你的SP。

如果您首先使用代码,也许这可以帮助您做同样的事情:https://msdn.microsoft.com/en-us/data/dn468673.aspx

答案 1 :(得分:0)

您可以使用 EntityAspect.setModified setDeleted setUnchanged 方法来完成此操作。即。

myEntity.entityAspect.setModified();

答案 2 :(得分:0)

您可以覆盖BeforeSaveEntities()。从地图中删除EntityState.Deleted的条目,并使用EntityState.Modified再次添加它们。你将需要微风v 1.3.3。

答案 3 :(得分:0)

一种当前的工作方式,不是很优雅,因为它使用反射,但比没有解决方案更好。

遵循我使用'ExclusionDate'属性的非常简化的方式:

// Model  -----------------------------------

public interface ISoftDelete
{
    DateTime? ExclusionDate { get; set; } 
}

public class Order : ISoftDelete
{
    // Props...
    public DateTime? ExclusionDate { get; set; }
}

// ------------------------------------------

// Data -------------------------------------

public interface IBreezeRepository<out T>
{
    IQueryable<T> All();
}

public class SoftRepository<T> : 
    IBreezeRepository<T> where T : class, ISoftDelete
{
    public SoftRepository(DbContext context)
    {
        Context = context;
    }

    protected DbContext Context { get; private set; }

    public IQueryable<T> All()
    {
        return Context.Set<T>().Where(p=> !p.ExclusionDate.HasValue);
    }
}

public class UnitOfWork
{
    private readonly EFContextProvider<EcmContext> _contextProvider;

    public UnitOfWork()
    {
        _contextProvider = new EFContextProvider<EcmContext>
        {
            BeforeSaveEntityDelegate = BeforeSaveEntity
        };

        var context = _contextProvider.Context;
        Orders = new SoftRepository<Order>(context);
    }

    public IBreezeRepository<Order> Orders { get; private set; }

    private bool BeforeSaveEntity(EntityInfo entityInfo)
    {
        var entityType = entityInfo.Entity.GetType();
        // a little reflection magic
        if (typeof(ISoftDelete).IsAssignableFrom(entityType) && 
            entityInfo.EntityState == EntityState.Deleted)
        {
            entityInfo.GetType().GetProperty("EntityState")
                      .SetValue(entityInfo, EntityState.Modified, null);
            var entity = entityInfo.Entity as ISoftDelete;
            if (entity != null)
            {
                entity.ExclusionDate = DateTime.Now;
                entityInfo.ForceUpdate = true;
            }
        }

        return true;
    }
}

// -------------------------------------------

请参阅:How to perform logical delete with Breeze JS?