هل من المقبول وضع بيانات البذور في طريقة OnmodelCreating في كود EF أولا؟

StackOverflow https://stackoverflow.com/questions/9528223

سؤال

أعرف كيفية القيام ببيانات البذور مع API للهجرة في EF 4.3.لقد كنت ألعب مع ذلك طوال الليل.ومع ذلك، فإن هدفي النهائي هو الحصول على مشروعي إلى النقطة التي يمكن للمستخدم فيها سحبها من مراقبة المصدر واضغط على F5 وهي جيدة للذهاب وقاعدة البيانات وبيانات البذور والجميع.

حاليا Code - يقوم أولا - يقوم أولا بوظيفة ممتازة في بناء DB على بناء جديد ولكن بيانات البذور غير مدرجة حتى أفعل قاعدة بيانات التحديث في وحدة تحكم Package Manager.عند هذه النقطة، يدير طريقة البذور وإدراج بيانات البذور الخاصة بي.

  1. هل من الجيد القيام بذلك فقط في طريقة onmodelcreating؟
  2. هل يمكنني الاستفادة من طريقة ملحق Addorupdate هنا؟
  3. هل سيتم تشغيل بيانات البذور هذه في كل مرة أضغط عليها F5؟إذا كان الأمر كذلك، فهل يمكنني اكتشاف ما إذا تم إنشاء DB بالفعل أم لا وضيف بيانات البذور فقط على إنشاء قاعدة البيانات الأولية؟
هل كانت مفيدة؟

المحلول

  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.

نصائح أخرى

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+

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top