如何获取标识列的主键



我使用以下代码在 MVC3 应用程序中创建审核跟踪。

http://jmdority.wordpress.com/2011/07/20/using-entity-framework-4-1-dbcontext-change-tracking-for-audit-logging/

在代码示例中,他们将 GUID 用于主键。就我而言,我使用的是自动递增的身份列。 上面链接中的代码效果很好,除了在调用 dbentry.current 值时,在"添加"上我无法获取主键(返回 0,因为 for 不会提交此数据)。

我正在尝试找到一种方法来获取主键,以便我可以正确地将其添加到我的交易表中。我知道您以后可以检索它,但我不确定获取它然后使用正确的主键更新表的最佳方法。

任何想法将不胜感激。我不希望将主键更改为 GUID。

我对我的数据库上下文进行了以下修改,该修改有效。

if (ent.State == System.Data.EntityState.Added)
            {
                base.SaveChanges();
                ent.State = System.Data.EntityState.Added;
            }

然后在 GetAuditRecordsForChange 函数中,我再次分离,因此记录不会创建两次。

if (dbEntry.State == System.Data.EntityState.Added)
        {
            // For Inserts, just add the whole record
            // If the entity implements IDescribableEntity, use the description from Describe(), otherwise use ToString()                   
            result.Add(new TransactionHistory()
            {
                TransactionTypeID = 1,
                TableName = tableName,
                FieldName = "ALL",
                RecordPK = dbEntry.CurrentValues.GetValue<object>(keyName).ToString(),
                OldValue = null,
                NewValue = (dbEntry.CurrentValues.ToObject() is IDescribableEntity) ? (dbEntry.CurrentValues.ToObject() as IDescribableEntity).Describe() : dbEntry.CurrentValues.ToObject().ToString(),
                TransactionBy = userId,
                TransactionDate = changeTime,
                TransactionApplication = "Galactus"
            });
            dbEntry.State = System.Data.EntityState.Detached;
        }

不能使用数据库生成的 PK 在单次运行中执行此操作。这就是帖子使用 GUID 的原因。要插入的记录的 PK 只有在插入 = 执行 SaveChanges 之后才知道。因此,您需要在此之后构建插入日志,然后再次SaveChanges

最新更新