0
모델에서 기본 키 이름을 가져 오려고하지만 데이터베이스가 Fluent API로 설계되었으며 발견 된 모든 예제는 DataAnnotation에서 설계되었습니다.C# - 감사 로그 - Fluent API로 설계된 모델에서 PK 이름을 얻는 방법?
DbContext의 SaveChanges()를 재정 의하여 감사 로그를 작성합니다.
감사 로그를 저장하는 코드입니다.
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;
}
ID_Registro 속성을 보면이 ID가 수신됩니다. 이 줄에서 keyName은 기본 키 필드의 이름을 지정해야합니다. 그리고이 줄은 저장된 ID가됩니다. 그러나이 필드는 기본 키를 찾을 수 없으므로 오류가 발생합니다.
어떻게 해결할 수 있습니까?
는 편집 :
이 모델이다. Codigo이 기본 키입니다. HasKey가 기본 키로 Codigo을 결정하고 모델에는 DataAnnotation이없는
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();
}
참고 :
public sealed class AcessoLogModel
{
public int Codigo { get; set; }
public int CodigoUsuario { get; set; }
public UsuarioModel Usuario { get; set; }
public string IP { get; set; }
public DateTime Horario { get; set; }
}
이
맵핑입니다.
이 NullReferenceException이 던져. EntityKeyValues가 null입니다. 내 모델을 추가하고 설명에 매핑하면 도움이 될 것입니다. –