【问题标题】:How to get primary key for identity column如何获取标识列的主键
【发布时间】:2012-06-23 20:12:57
【问题描述】:

我正在使用以下代码在 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。

我对我的 dbcontext 进行了以下修改。

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;
        }

【问题讨论】:

    标签: asp.net-mvc-3 entity-framework


    【解决方案1】:

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

    【讨论】:

    • 谢谢,我做了一些小的改动,效果很好。如果添加了实体状态,我会保存更改,然后将状态设置回已添加,以便逻辑继续适用于审计功能,但在添加审计后分离。这似乎工作正常。
    猜你喜欢
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    相关资源
    最近更新 更多