实体框架ObjectStateEntries按顺序/保存顺序排序

时间:2011-06-20 05:02:12

标签: .net entity-framework entity-framework-4

我需要按照它们将被保存的顺序从我的ObjectStateManager中获取所有ObjectStateEntries(按照依赖顺序)。有没有简单的方法呢?

感谢。

1 个答案:

答案 0 :(得分:1)

是的,如果是Entity Framework,有一种方法可以插入保存过程,以便执行一些自定义逻辑。

这是一个如何扩展简单的NorthwindEntities模型并在添加/更新/删除过程中做一些工作的示例:

public partial class NorthwindEntities
{
    partial void OnContextCreated()
    {
        SavingChanges += OnSavingChanges;
    }

    private void OnSavingChanges(object sender, EventArgs e)
    {
        var context = sender as NorthwindEntities;

        if (context != null)
        {
            context.DetectChanges();

            var objectStateManager = context.ObjectStateManager;

            foreach (var entry in objectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted))
            {
                switch (entry.State)
                {
                    case EntityState.Added:
                        // Perform custom 'add' logic here
                        break;
                    case EntityState.Modified:
                        // Perform custom 'update' logic here
                        break;
                    case EntityState.Deleted:
                        // Perform custom 'delete' logic here
                        break;
                }
            }
        }
    }
}