45 lines
2.1 KiB
C#
45 lines
2.1 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
|
|
|
public class ObservationConfiguration : IEntityTypeConfiguration<Observation>
|
|
{
|
|
public void Configure(EntityTypeBuilder<Observation> builder)
|
|
{
|
|
builder.ToTable("observations", t =>
|
|
{
|
|
t.HasCheckConstraint("chk_observations_source",
|
|
"source IN ('MANUAL', 'DEVICE', 'LAB')");
|
|
});
|
|
builder.HasKey(o => o.Id);
|
|
builder.Property(o => o.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()");
|
|
builder.Property(o => o.EncounterId).HasColumnName("encounter_id");
|
|
builder.Property(o => o.ObservationCode).HasColumnName("observation_code").HasMaxLength(50).IsRequired();
|
|
builder.Property(o => o.Value).HasColumnName("value").HasColumnType("decimal(10,3)").IsRequired();
|
|
builder.Property(o => o.Unit).HasColumnName("unit").HasMaxLength(20).IsRequired();
|
|
builder.Property(o => o.Source)
|
|
.HasColumnName("source")
|
|
.HasMaxLength(20)
|
|
.HasConversion(
|
|
v => v.ToDbString(),
|
|
v => ObservationSourceExtensions.FromDbString(v))
|
|
.HasDefaultValueSql("'MANUAL'")
|
|
.HasSentinel((ObservationSource)(-1));
|
|
builder.Property(o => o.IdempotencyKey).HasColumnName("idempotency_key").HasMaxLength(100);
|
|
builder.Property(o => o.RecordedAt).HasColumnName("recorded_at");
|
|
builder.Property(o => o.CreatedAt).HasColumnName("created_at").HasDefaultValueSql("NOW()");
|
|
|
|
builder.HasOne(o => o.Encounter)
|
|
.WithMany(e => e.Observations)
|
|
.HasForeignKey(o => o.EncounterId)
|
|
.OnDelete(DeleteBehavior.Restrict);
|
|
|
|
// Partial unique index — only non-null idempotency keys are checked for uniqueness.
|
|
// Devices that do not send a key are not subject to deduplication.
|
|
builder.HasIndex(o => o.IdempotencyKey)
|
|
.IsUnique()
|
|
.HasFilter("idempotency_key IS NOT NULL");
|
|
|
|
builder.HasIndex(o => new { o.EncounterId, o.ObservationCode, o.RecordedAt });
|
|
}
|
|
}
|