Frage

Ich weiß, wie man Samendaten mit den Migrations-API in EF 4.3 ausführt.Ich habe die ganze Nacht damit gespielt.Mein ultimatives Ziel ist jedoch, mein Projekt auf den Punkt zu bringen, an dem ein Benutzer ihn von der Quellsteuerung ziehen kann, und drücken Sie F5, und sie sind gut zu gehen, Datenbank-, Saatgutdaten und alle.

Derzeit ist derzeit Code-zuerst eine hervorragende Aufgabe, den DB auf einem frischen Build zu errichten, aber Samendaten werden erst in die Aktualisierungsdatenbank in der Paketmanager-Konsole eingefügt.An diesem Punkt läuft es die Samenmethode und fügt meine Saatgutdaten ein.

    .
  1. ist es in Ordnung, das in der Onmodelcreate-Methode einfach zu tun?
  2. Kann ich hier noch die Addorupdate-Erweiterungsmethode nutzen?
  3. Werden diese Samendaten jedes Mal ausgeführt, wenn ich F5 drücke?Wenn ja, kann ich erkennen, ob der dB bereits erstellt wurde oder nicht und nur diese Samendaten zur ersten Datenbankerstellung hinzufügen?
War es hilfreich?

Lösung

  1. No. OnModelCreating is executed every time the model definition must be built = every time you start the application and use data access for the first time. It may be nice in your development environment but it is not nice in production. Moreover you cannot use context while it is constructed so the only way how to seed data in this method is using SQL directly.
  2. AddOrUpdate is mostly for migrations. It has hidden costs (reflection and query to database) so use it carefully.
  3. You can detect it by manually executing SQL query (you cannot use Database.Exists inside OnModelCreating - again because this method is not available when context is being constructed) but it is something that doesn't belong to OnModelCreating => single responsibility pattern.

There are better ways how to do this.

  • MigrateDatabaseToLatestVersion database initializer in EF 4.3 will run your migration set if database doesn't exist or update existing database
  • You can use DbMigrator class at bootstrap of your application and migrate your database to the last version with the higher control over whole process
  • I didn't check if it is possible but you should be able to modify MSBuild or add pre build action to your project which will either somehow use power shell commands or execute custom console application using DbMigrator class.

Andere Tipps

What is wrong with seeding data in the overridden Seed() method when inheriting from CreateDatabaseIfNotExists class?

It worked with EF 4.2 and below and seems to still be working with EF 4.3+

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top