【问题标题】:MVC Enity Framework get KEY attribute from tableMVC 实体框架从表中获取 KEY 属性
【发布时间】:2014-09-06 15:37:16
【问题描述】:

我正在尝试从表中提取 [key] 值。

这是一个如下所示的日志记录方法:

private List<Log> GetAuditRecordsForChange(DbEntityEntry dbEntry, string userId)
{
    List<Log> result = new List<Log>();

    DateTime changeTime = DateTime.Now;

    // Get the Table() attribute, if one exists
    TableAttribute tableAttr = dbEntry.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), false).SingleOrDefault() as TableAttribute;

    // Get table name (if it has a Table attribute, use that, otherwise get the pluralized name)
    string tableName = tableAttr != null ? tableAttr.Name : dbEntry.Entity.GetType().Name;

    // Get primary key value
    string keyName = dbEntry.Entity.GetType().GetProperties().Single(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Count() > 0).Name;

    if (dbEntry.State == EntityState.Added)
    {
        result.Add(new Log()
        {
            LogID = Guid.NewGuid(),
            EventType = "A", // Added
            TableName = tableName,
            RecordID = dbEntry.CurrentValues.GetValue<object>(keyName).ToString(), 
            ColumnName = "*ALL",
            NewValue = (dbEntry.CurrentValues.ToObject() is IDescribableEntity) ? (dbEntry.CurrentValues.ToObject() as IDescribableEntity).Describe() : dbEntry.CurrentValues.ToObject().ToString(),
            Created_by = userId,
            Created_date = changeTime
        }
            );
    }

问题是在添加记录时获取 RecordID,当它被删除或修改时它可以工作。 (获取代码相同)

当我调试时,我还看到它在 CustomAttributes 基础中有 KeyAttribute,但不确定为什么它总是显示为 0。

如果需要,我可以调试更多

【问题讨论】:

    标签: asp.net-mvc database entity-framework audit


    【解决方案1】:

    在 savechanges 之后,您可以获取新创建的密钥。 (猜测key是自动生成插入一条新记录)。

    【讨论】:

    • 啊哈,是的,它是自动生成的。那我该怎么做呢?
    【解决方案2】:

    对我来说,你有几个解决方案。

    第一个解决方案:

    • 从上下文中登记添加的实体
    • 保存更改
    • 枚举登记实体以添加日志
    • 保存更改

    这里的问题(或不是)是业务和日志记录不在同一个事务中。

    另一个问题,取决于实现,是防止记录日志的日志...这可以通过例如按 typeName 过滤实体来完成。

    其他解决方案:

    向您的实体添加和 ICollection

    这里的问题是统一日志:

    • 实体的继承,或
    • 几个日志表 + 一个视图
    • ...

    其他解决方案

    在数据库级别使用触发器

    其他解决方案

    ...,如果您有 Sql Server 企业版,请使用 cdc

    【讨论】:

    • 嗯,所以不可能在第一次 SavingChanges 之后只更新 RecordID 字段?我怎样才能将其编码为不记录?一些例子会很棒。
    • 想过一件事,但怀疑它的好做法。当您创建新记录时,只需将其添加到没有值的数据库(NULL)(将缺少 [必需] 标记)然后只更新新创建的行,然后不监听新添加的行,只需监听更新的行.不是我真正想做的事,但那行得通吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多