How do I view an entityset and uncommitted changes?

我只是一个虾纸丫 提交于 2019-12-07 18:46:24

问题


I'm using EF4 and when debugging, I want to see what changes are about to be made to the database. For example, if I add a bunch of new entities, like contacts, I want to see the list of contacts that will be added when .SaveChanges() executes. Likewise, if deletions will occur, it would be nice to see what will be deleted.

Is there a visualizer or similar tool in VS2010 that does this?

Thanks!


回答1:


That is not visible directly. The best place is check ObjectStateManager which holds state entries for each entity and independent association. Each ObjectStateEntry representing entity has Entity property filled.

Edit:

The former description is useful if you want to access these data in code. If you just want to see it in debugger add context.ObjectStateManager to the watch window and navigate to Non-Public members. You will see fields like:

  • _addedEntityStore
  • _deletedEntityStore
  • _modifiedEntityStore



回答2:


I use this code to notify pending changes, it might be useful (context is variable for ModelContext):

var changes = new[] { EntityState.Added, EntityState.Deleted, EntityState.Modified }
    .SelectMany(state => context.ObjectStateManager.GetObjectStateEntries(state)
                            .Select(entry => new
                                     {
                                   NewState = state.ToString(),
                                   EntitySetName = entry.EntitySet.Name,
                                   Object = ((entry.Entity == null) ? "<n/a>" : entry.Entity.ToString()),
                                   IsRelation = entry.EntitySet.Name.StartsWith("FK_"),
                                     }))
            .OrderBy(x => x.IsRelation ? 1 : 0)
            .Select(x => string.Format("{0} ({1}): {2}", x.NewState, x.EntitySetName, x.Object))
            .ToArray();

After that you can aggregate this string and show MessageBox or notify user as you do in your App (For example output to some textbox like 'Output')



来源:https://stackoverflow.com/questions/5719990/how-do-i-view-an-entityset-and-uncommitted-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!