C#-审核日志-如何从使用Fluent Api设计的模型中获取PK名称?
我试图在模型中获得主键名称,但我的数据库是用Fluent Api设计的,我找到的所有示例都是用DataAnnotation设计的 我正在重写DbContext的SaveChanges()以创建审核日志 这是保存审核日志的代码C#-审核日志-如何从使用Fluent Api设计的模型中获取PK名称?,c#,entity-framework,ef-fluent-api,C#,Entity Framework,Ef Fluent Api,我试图在模型中获得主键名称,但我的数据库是用Fluent Api设计的,我找到的所有示例都是用DataAnnotation设计的 我正在重写DbContext的SaveChanges()以创建审核日志 这是保存审核日志的代码 private List<AuditLogModel> GetAuditRecordsForChange(DbEntityEntry dbEntry, int? id_usuario = null) { List<AuditLogM
private List<AuditLogModel> GetAuditRecordsForChange(DbEntityEntry dbEntry, int? id_usuario = null)
{
List<AuditLogModel> result = new List<AuditLogModel>();
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 (If you have more than one key column, this will need to be adjusted)
//string keyName = dbEntry.Entity.GetType().GetProperties().Single(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Count() > 0).Name;
var oc = ((IObjectContextAdapter)this).ObjectContext;
EntityKey key = oc.ObjectStateManager.GetObjectStateEntry(dbEntry.Entity).EntityKey;
string keyName = key.EntitySetName;
if (dbEntry.State == 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 AuditLogModel()
{
Id_Usuario = id_usuario,
Id_Registro = (int)dbEntry.CurrentValues.GetValue<object>(keyName), // Again, adjust this if you have a multi-column key
EventoTipo = "I", // INSERT
Tabela = tableName,
NovoValor = dbEntry.CurrentValues.ToObject().ToString()
});
//NovoValor = (dbEntry.CurrentValues.ToObject() is IDescribableEntity) ? (dbEntry.CurrentValues.ToObject() as IDescribableEntity).Describe() : dbEntry.CurrentValues.ToObject().ToString()
}
// Otherwise, don't do anything, we don't care about Unchanged or Detached entities
return result;
}
这是映射:
public AcessoLogMapping()
{
ToTable("TB_ACESSO_LOG");
HasKey(x => x.Codigo);
Property(x => x.Codigo).HasColumnName("ID_ACESSO_LOG")
.HasColumnType("INT")
.IsRequired();
Property(x => x.CodigoUsuario).HasColumnName("ID_USUARIO_ACESSO_LOG")
.HasColumnType("INT")
.IsRequired();
HasRequired(x => x.Usuario)
.WithMany()
.HasForeignKey(x => x.CodigoUsuario)
.WillCascadeOnDelete(false);
Property(x => x.Horario).HasColumnName("HORARIO_ACESSO_LOG")
.HasColumnType("DATETIME")
.IsRequired();
Property(x => x.IP).HasColumnName("IP_ACESSO_LOG")
.HasColumnType("VARCHAR")
.HasMaxLength(180)
.IsRequired();
}
请注意,HasKey将Codigo确定为主键,并且模型中没有DataAnnotation。这似乎适用于我:
Id_Registro = entry.State == EntityState.Added ? null : ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity).EntityKey.EntityKeyValues[0].Value.ToString()
这将引发NullReferenceException。EntityKeyValues为空。我在描述中添加了我的模型和映射,可能会有所帮助。
Id_Registro = entry.State == EntityState.Added ? null : ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity).EntityKey.EntityKeyValues[0].Value.ToString()