Ich versuche, die automatische Speicherfunktion von EntityFramework Plus einzurichten , aber es sieht so aus, als ob ich an etwas sehr Dummem festgefahren bin. Ich folge dem Pfad "Automatisch speichern durch Überschreiben von SaveChanges & SaveChangesAsync", aber ich versuche, Code-first als das Projekt zu verwenden, für das ich das verwenden werde, das jetzt schon eine Weile so läuft. Trotzdem sieht mein DbContext so aus:
public class CadastralDbContext : DbContext
{
public CadastralDbContext(DbContextOptions<CadastralDbContext> options) : base(options) { }
static CadastralDbContext()
{
AuditManager.DefaultConfiguration.AutoSavePreAction = (context, audit) =>
(context as CadastralDbContext).AuditEntries.AddRange(audit.Entries);
}
public DbSet<AuditEntry> AuditEntries { get; set; }
public DbSet<AuditEntryProperty> AuditEntryProperties { get; set; }
//Ommited my DbSets
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(CadastralDbContext).Assembly);
/*** Ignore these for now ***/
//modelBuilder.Entity<AuditEntry>().Ignore(x => x.Properties);
//modelBuilder.Entity<AuditEntryProperty>().Ignore(x => x.Parent);
}
public override int SaveChanges()
{
var audit = new Audit();
audit.PreSaveChanges(this);
var rowAffecteds = base.SaveChanges();
audit.PostSaveChanges();
if (audit.Configuration.AutoSavePreAction != null)
{
audit.Configuration.AutoSavePreAction(this, audit);
base.SaveChanges();
}
return rowAffecteds;
}
public async Task<int> SaveChangesAsync()
{
return await SaveChangesAsync(CancellationToken.None);
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
var audit = new Audit();
audit.PreSaveChanges(this);
var rowAffecteds = await base.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
audit.PostSaveChanges();
if (audit.Configuration.AutoSavePreAction != null)
{
audit.Configuration.AutoSavePreAction(this, audit);
await base.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
}
return rowAffecteds;
}
}
}}
Grundsätzlich, was das Tutorial mit hinzugefügten DbSet<AuditEntry>
und DbSet<AuditEntryProperty>
die Klassen aus dem Framework selbst sind. Wenn wir Metadaten auf diese untersuchen, haben wir:
//
// Summary:
// An audit entry.
public class AuditEntry
{
//
// Summary:
// Gets or sets the object state entry.
[NotMapped]
public object Entity;
//
// Summary:
// Gets or sets the object state entry.
[NotMapped]
public EntityEntry Entry;
//
// Summary:
// Gets or sets the parent.
public Audit Parent;
public AuditEntry();
//
// Summary:
// Gets or sets the identifier of the audit entry.
[Column(Order = 0)]
public int AuditEntryID { get; set; }
//
// Summary:
// Gets or sets who created this object.
[Column(Order = 5)]
[MaxLength(255)]
public string CreatedBy { get; set; }
//
// Summary:
// Gets or sets the the date of the changes.
[Column(Order = 6)]
public DateTime CreatedDate { get; set; }
//
// Summary:
// Gets or sets the name of the entity set.
[Column(Order = 1)]
[MaxLength(255)]
public string EntitySetName { get; set; }
//
// Summary:
// Gets or sets the name of the entity type.
[Column(Order = 2)]
[MaxLength(255)]
public string EntityTypeName { get; set; }
//
// Summary:
// Gets or sets the properties.
public List<AuditEntryProperty> Properties { get; set; }
//
// Summary:
// Gets or sets the entry state.
[Column(Order = 3)]
public AuditEntryState State { get; set; }
//
// Summary:
// Gets or sets the name of the entry state.
[Column(Order = 4)]
[MaxLength(255)]
public string StateName { get; set; }
}
Und
//
// Summary:
// An audit entry property.
public class AuditEntryProperty
{
//
// Summary:
// Gets or sets the new value audited.
[NotMapped]
public PropertyEntry PropertyEntry;
public object NewValue;
public object OldValue;
public AuditEntryProperty();
//
// Summary:
// Gets or sets the name of the property internally.
[NotMapped]
public string InternalPropertyName { get; set; }
//
// Summary:
// Gets or sets a value indicating whether OldValue and NewValue is set.
[NotMapped]
public bool IsValueSet { get; set; }
//
// Summary:
// Gets or sets the name of the relation audited.
[Column(Order = 2)]
[MaxLength(255)]
public string RelationName { get; set; }
//
// Summary:
// Gets or sets the name of the property audited.
[Column(Order = 3)]
[MaxLength(255)]
public string PropertyName { get; set; }
//
// Summary:
// Gets or sets the parent.
public AuditEntry Parent { get; set; }
//
// Summary:
// Gets or sets the identifier of the audit entry property.
[Column(Order = 0)]
public int AuditEntryPropertyID { get; set; }
//
// Summary:
// Gets or sets the new value audited formatted.
[Column("NewValue", Order = 5)]
public string NewValueFormatted { get; set; }
//
// Summary:
// Gets or sets the identifier of the audit entry.
[Column(Order = 1)]
public int AuditEntryID { get; set; }
//
// Summary:
// Gets or sets the old value audited formatted.
[Column("OldValue", Order = 4)]
public string OldValueFormatted { get; set; }
}
Es sieht gut genug aus, außer für zwei Eigenschaften: public List<AuditEntryProperty> Properties { get; set; }
und public AuditEntry Parent { get; set; }
. Da sie nicht als virtual
markiert sind, schlägt das Hinzufügen einer Migration fehl. Ich habe eine Problemumgehung versucht, um zu sehen, ob ich die Tabellen generieren kann, und ich war tatsächlich erfolgreich (diese Zeilen wurden zuvor kommentiert):
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//...
modelBuilder.Entity<AuditEntry>().Ignore(x => x.Properties);
modelBuilder.Entity<AuditEntryProperty>().Ignore(x => x.Parent);
}
Dies scheint die PrimaryKey-ForeignKey-Beziehung beider Tabellen zu deaktivieren, die im Framework selbst eingerichtet sind, da es keinen Hinweis darauf gibt, dass ich dies manuell tun sollte. Ich habe sogar versucht, das Skript auszuführen, um zu sehen, was daraus werden würde, und die Ergebnisse waren katastrophal:
CREATE INDEX [IX_AuditEntryID] ON [dbo].[AuditEntryProperties]([AuditEntryID])
GO
ALTER TABLE [dbo].[AuditEntryProperties]
ADD CONSTRAINT [FK_dbo.AuditEntryProperties_dbo.AuditEntries_AuditEntryID]
FOREIGN KEY ([AuditEntryID])
REFERENCES [dbo].[AuditEntries] ([AuditEntryID])
ON DELETE CASCADE
GO
Das brachte mir beim Einfügen den folgenden SQL-Fehler: String or binary data would be truncated
. Also habe ich gerade zum vorherigen Status zurückgekehrt, in dem das Framework eine "50% -Ausgabe" hat, da es Datensätze in der AuditEntry-Tabelle (die Daten wie die Tabelle enthält) speichert, wenn ein Benutzer aber Einfüge-, Aktualisierungs- oder Löschvorgänge anfordert In den AuditEntryProperties (neuer Wert, alter Wert, Spalte) wird nichts beibehalten, und ich kann mir nichts anderes vorstellen, als dass diese Eigenschaften ignoriert werden, um die Ursache für all dies zu sein.
Ich dachte, ich könnte sowohl AuditEntry als auch AuditEntryProperties überschreiben, aber das klingt nach einer großen, dummen Problemumgehung. Ich bin kein DB-Experte, was vermisse ich hier?
Bearbeiten : Vergessen, den Migrationscode hinzuzufügen:
migrationBuilder.CreateTable(
name: "AuditEntries",
columns: table => new
{
AuditEntryID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
CreatedBy = table.Column<string>(maxLength: 255, nullable: true),
CreatedDate = table.Column<DateTime>(nullable: false),
EntitySetName = table.Column<string>(maxLength: 255, nullable: true),
EntityTypeName = table.Column<string>(maxLength: 255, nullable: true),
State = table.Column<int>(nullable: false),
StateName = table.Column<string>(maxLength: 255, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AuditEntries", x => x.AuditEntryID);
});
migrationBuilder.CreateTable(
name: "AuditEntryProperties",
columns: table => new
{
AuditEntryPropertyID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
AuditEntryID = table.Column<int>(nullable: false),
PropertyName = table.Column<string>(maxLength: 255, nullable: true),
RelationName = table.Column<string>(maxLength: 255, nullable: true),
NewValue = table.Column<string>(nullable: true),
OldValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AuditEntryProperties", x => x.AuditEntryPropertyID);
});
Bearbeiten 2 Versucht, die FK mit Fluent API hinzuzufügen:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(CadastralDbContext).Assembly);
modelBuilder.Entity<AuditEntryProperty>().HasOne<AuditEntry>(prop => prop.Parent).WithMany(a => a.Properties).HasForeignKey(prop => prop.AuditEntryID);
}
Die Migration kann immer noch nicht durchgeführt werden, da diese Eigenschaften nicht virtuell sind.
Wir haben ein Problem im EF Plus Issues Tracker erstellt
Hier finden Sie ein Projekt, das Sie ausprobieren können. Ich schlage vor, Sie setzen die Diskussion über unseren Issue Tracker fort, da Stack Overflow keine Plattform für diese Art von Problem ist.