Automatically migration through code when using the Entity Framework Core

Source: Internet
Author: User

When using the Entity Framework Core, automatic migration is introduced by code

When developing with the Entity Framework Core (called the EF core bar), if the model is changed, we will manually migrate the command-line tools provided with EF Core before running the program. But for efficiency, I would like to be able to migration at the entrance of the program? It should be possible from a personal experience, since the EF Tool provides the CLI but it is eventually parsed by the program. The following is the beginning of the analysis, how to migration through the code.

Second analysis

First we need to understand that there are two steps to take when using the EF Core CLI:

First step: Generate the migration file;

The second step: update the changes to the database;

Since it is Mr. Migration file re-update, there must be a corresponding module in EF Core to do this thing. Let's look at the structure of the EF Core project. We did find the module about migration. As we can see in the class name of the Migrations/design directory, it is the generation of the migration file. This is the first place here.

  

Found the portal to generate the migration file, let's find out how to update these changes to the database through code.

When using EF Core, we have to write our own DbContext subclasses by inheriting DbContext. In the DbContext class we found a Database property. As shown in the following:

  

Then we looked at the Databasefacde class and did not find any functions to perform the migration. With code search, I have a migration () extension method in the Relationaldatabasefacadeextensions class. With the comment parsing, I also determined that it was executing the migration file and updating the changes to the database.

We've found the code for both of these steps, and we're going to write a code that will automatically update the model changes to the database.

 1 public class Automigration 2 {3 private readonly IServiceProvider _serviceprovider; 4 private Informationdbcon Text _context;         5 6 Public automigration (IServiceProvider serviceprovider) 7 {8 _serviceprovider = serviceprovider; 9 _context = serviceprovider.getservice<informationdbcontext> ();}11 public void Migrator () 13 { var path = Path.Combine (Appcontext.basedirectory, "... \\.. \\.. \\Migrations\\ "); Directory.Exists (Path), Directory.CreateDirectory (path),}19 else20 {2 1 directory.getfiles (PATH). ToList (). ForEach (file.delete);}23 using (_context) (+ var services = (iinfrastructure <IServiceProvider>) (_context). instance;27 var codehelper = new Csharphelper (); var scaffolder = Activatorutilities.createinsta Nce<migrationsscaffolder> (services,29 NewCsharpmigrationsgenerator (Codehelper, New Csharpmigrationoperationgenerator (Codehelper), new CSharpS Napshotgenerator (Codehelper)); var projectdir = Path.Combine (Path, "...) \ \ "), var migrationassembly = new migrationsassembly (new Currentdbcontext (_context), _context. Options, New Migrationsidgenerator ()); scaffolder. GetType (). GetField ("_migrationsassembly", BindingFlags.Instance | BindingFlags.NonPublic). SetValue (scaffolder, migrationassembly); var readonlydic = new Readonlydictionary<string,typeinfo> ( New dictionary<string, typeinfo> ()); PNs Migrationassembly.gettype (). GetField ("_migrations", BindingFlags.NonPublic | bindingflags.instance). SetValue (migrationassembly, New lazyref<ireadonlydictionary<string, typeinfo>> (readonlydic)); R migration = scaffolder. Scaffoldmigration ("Information.migrations", "Information"), and scaffolder. Save (ProjectDir, Migration, path); 41 42//Another way to save the//file.writealltext ($ "migrations\\{migration. Migrationid}{migration. FileExtension} ", migration. MigrationCode)//file.writealltext ("migrations\\" +45//migration. Migrationid + ". Designer "+ migration. fileextension,46//migration. Metadatacode)//file.writealltext ("migrations\\" + migration. Snapshotname + migration. fileextension,48//migration. Snapshotcode);}50 using (_context = (informationdbcontext) _SERVICEPROVIDER.GETSERVICE&LT;IDBCONTEXT&G t; ()) _context. Database.migrate (); 54}55}56}

Another point of note: We need to specify the project where the migrated files are located.

1 services. Adddbcontext<informationdbcontext> (opt =>2 {3     var connectionString = configuration["ConnectionStrings :D efaultconnection "];4     opt. Usesqlserver (connectionString, Optionbuilder =>5     {6         optionbuilder.migrationsassembly ("Information"); 7     }); 8});

Three summary

As you can see from the above analysis, we are actually implementing the CLI's two commands through the code. The call can be made in the Startup file. Why do you want to do this? Because in the actual development time, back and forth to switch the window heart feel uncomfortable bai. :)

Automatically migration through code when using the Entity Framework Core

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.