0

我有几个与DbContext. 如何SaveChanges根据正在保存的模型覆盖以执行不同的操作?

例如,假设我有两个模型,Document并且Paragraph. 如何覆盖SaveChanges以便在添加 a 时创建目录并在Document添加 a 时创建文件Paragraph

到目前为止,这是我这样做的尝试。

public int override SaveChanges()
{
    ChangeTracker.DetectChanges();

    var context = ((IObjectContextAdapter)this).ObjectContext;
    var stateEntries = context.ObjectStateManager.GetObjectStateEntries(
        EntityState.Added
        | EntityState.Modified
        | EntityState.Deleted
    ).ToList();

    foreach (var entry in stateEntries)
    {
        if (!entry.IsRelationship)
        {
            switch (entry.State)
            {
                case EntityState.Added:
                    break;

                case EntityState.Modified:
                    break;

                case EntityState.Deleted:
                    break;
            }
        }
    }

    return base.SaveChanges();
}
4

1 回答 1

2

该条目具有Entity保存已处理实体实例的属性,因此您可以检查实例的类型并理论上执行您想要执行的任何逻辑。


You should not use SaveChanges to do anything else than processing your entities for persistence to database - that breaks the separation of concerns. The context is adapter between your application logic and database - nothing more. Moreover whole this idea of integrating file system operations with database operations needs much more complex and careful handling to solve the situation when any operation fails. In your current scenario any failure in call to base.SaveChanges will result in orphan directories or files in your file system - you need to use transactional file system and run but database and file system operation in the same transaction or you must implement manual file system compensation.

您的代码的另一个问题是您必须先处理Document实例,Paragraph以确保在要插入文件等之前创建目录。这个逻辑不属于SaveChanges方法,不应该从SaveChanges方法中调用。

于 2012-04-09T22:32:00.557 回答