【问题标题】:Obtaining List of Entities in DataContext获取DataContext中的实体列表
【发布时间】:2013-04-25 19:10:41
【问题描述】:

获取在给定 EF 4.1 DbContext 中加载的实体列表的最佳方法是什么?我尝试定位为给定上下文加载的DbEntityEntry.Entity 对象的集合没有成功。似乎应该可以使用类似于DbContext.ChangeTracker.Entries() 操作方式的模式。

【问题讨论】:

    标签: entity-framework entity-framework-4 ef4-code-only


    【解决方案1】:

    这将为您提供上下文中的所有实体:

    dbContext.ChangeTracker.Entries().Select(e => e.Entity)
    

    但你会得到它们的类型为一般Object

    【讨论】:

      【解决方案2】:

      这是我使用的例程测试,因此我可以检查所有条目的值和状态。

      public static void ContextDumpTest(DbContext context) {
      
             Debug.WriteLine("====Begin Context Dump========");
             var dbsetList = context.ChangeTracker.Entries();
              foreach (var dbEntityEntry in dbsetList) {
      
                  Debug.WriteLine(dbEntityEntry.Entity.GetType().Name + " => " + dbEntityEntry.State );
                  switch (dbEntityEntry.State) {
                       case EntityState.Detached:
                       case EntityState.Unchanged:
                       case EntityState.Added:
                       case EntityState.Modified:
                          WriteCurrentValues(dbEntityEntry);
                           break;
                      case EntityState.Deleted:
                           WriteSomeValues(dbEntityEntry);
                           break;
                      default:
                          throw new ArgumentOutOfRangeException();
                  }
                   Debug.WriteLine("==========End of Entity======");
              }
              Debug.WriteLine("==========End of Context======");
          }
      
          private static void WriteCurrentValues(DbEntityEntry dbEntityEntry) {
              foreach (var cv in dbEntityEntry.CurrentValues.PropertyNames) {
                  Debug.WriteLine(cv + "=" + dbEntityEntry.CurrentValues[cv]);
              }
          }
          private static void WriteSomeValues(DbEntityEntry dbEntityEntry)
          {
              foreach (var cv in dbEntityEntry.OriginalValues.PropertyNames)
              {
                  Debug.WriteLine(cv + "=" + dbEntityEntry.OriginalValues[cv]);
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2011-10-06
        • 2010-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-18
        相关资源
        最近更新 更多