Is it permissible to put seed data first in the OnModelCreating method in EF code?

I know how to make source data using the migration API in EF 4.3. I play with this all night. However, my ultimate goal is to bring my project to the point where the user can pull it out of the control source and press F5, and they are good for searching, database, seed data, etc.

Currently, the first code does an excellent job of creating a database on a new build, but the seed data is not inserted until I update the database in the package manager console. At this point, he starts the seed method and inserts my seed data.

  • Is it possible to just do this in the OnModelCreating method?
  • Can I use the AddOrUpdate extension method here?
  • Will this seed data be executed every time I press F5? If so, can I determine if the database has already been created or not, and only add this source data when creating the initial database?
+4
source share
2 answers
  • Not. OnModelCreating is done every time a model definition needs to be built = every time you launch the application and use data access for the first time. It may be good in your development environment, but it is not pleasant in production. Moreover, you cannot use the context during its construction, therefore the only way how data seeds in this method directly uses SQL.
  • AddOrUpdate is mainly for porting . It has hidden costs (reflection and query to the database), so use it carefully.
  • You can detect this by executing the SQL query manually (you cannot use Database.Exists inside OnModelCreating - again, because this method is not available when building the context), but this is something that does not apply to OnModelCreating => a single responsibility template.

There are better ways to do this.

  • MigrateDatabaseToLatestVersion database initializer in EF 4.3 will start your migration set if the database does not exist or does not update the existing database
  • You can use the DbMigrator class when loading the application and transfer your database to the latest version with more control over the whole process.
  • I did not check if this is possible, but you should be able to modify MSBuild or add a pre build project to the project, which will somehow use shell commands, or execute your own console application using the DbMigrator class.
+9
source

What happens with data visiting in the overridden Seed () method when inheriting the CreateDatabaseIfNotExists class?

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

+2
source

Source: https://habr.com/ru/post/1399315/


All Articles