asp.net Core 2.0+entityframeworkcore 2.0 Add Data Migration

Source: Internet
Author: User
Tags static class


Core
asp.net core because of the widespread use of dependency injection, configuration data migration, and asp.net is very different, this article describes the ASP.net Core to add data migration process



Add NuGet Package



Install-package Microsoft.EntityFrameworkCore.SqlServer



Install-package Microsoft.EntityFrameworkCore.Tools



Install-package Microsoft.EntityFrameworkCore.Design



First create a new Model class User:


public class User

    {

        //user number (from growth primary key)

        [key] public

        long UserId {get; set;}



        User name (required)

        [MaxLength, Required] public

        string UserName {get; set;}



        Password (required)

        [MaxLength, DataType (Datatype.password), Required] public

        string Password {get; set;}

    }


Then set up the Mydbcontext class


   public class Blogdbcontext:dbcontext {//due to dependency injection, no constructor here will be a warning, but does not affect the establishment of data migration files, update the database does not affect the public Blog  DbContext (dbcontextoptions<blogdbcontext> options): Base (Options) {} protected override void onconfiguring (Dbcontextoptionsbuilder builder) {//Add database connection string Builder. Usesqlserver (@ "server=.; User Id=sa;

        Password=123;database=blogdbcontext "); } protected override void Onmodelcreating (ModelBuilder builder) {base.



            Onmodelcreating (builder); Add Fluentapi Configure var typestoregister = assembly.getexecutingassembly (). GetTypes (). Where (q => q.getinterface (typeof (Ientitytypeconfiguration<>).



            FullName)!= null); foreach (var type in typestoregister) {Dynamic configurationinstance = Activator.createinsta

                NCE (type); Builder.

            ApplyConfiguration (configurationinstance);

 }       //user related tables Public dbset<user> the Users {get; set;}
 }public class BlogDbContext: DbContext

    {

    // Due to the dependency injection, there will be a warning here without the constructor, but it does not affect the establishment of the data migration file, and it does not affect the update of the database.

        public BlogDbContext (DbContextOptions <BlogDbContext> options): base (options)

        {

        }



        protected override void OnConfiguring (DbContextOptionsBuilder builder)

        {

            // Add database connection string

            builder.UseSqlServer (@ "Server = .; User id = sa; Password = 123; Database = BlogDbContext");

        }



        protected override void OnModelCreating (ModelBuilder builder)

        {

            base.OnModelCreating (builder);



            // Add FluentAPI configuration

            var typesToRegister = Assembly.GetExecutingAssembly (). GetTypes (). Where (q => q.GetInterface (typeof (IEntityTypeConfiguration <>). FullName)! = null);



            foreach (var type in typesToRegister)

            {

                dynamic configurationInstance = Activator.CreateInstance (type);

                builder.ApplyConfiguration (configurationInstance);

            }

        }

        // User related table

        public DbSet <User> Users {get; set;}

    } 


Then configure Appsetting.json to add the database connection string:


      "connectionstrings": {"

        defaultconnection": "server=.; User Id=sa; Password=123;database=blogdbcontext; "

      },


To inject the database service into the Startup.cs file:


        public void Configureservices (iservicecollection services)

        {

            services. adddbcontext<blogdbcontext> (Options => 
                                                 options. Usesqlserver ("defaultconnection"));
            Services. Addmvc ();

        }


Data migration can then be made, as the ASP. NET Core defaults to open Data migration, so you can add data migration directly



Add-migration Init



Add the seed data below, and here you have to say one of the big pits that has been trampled, add seed data when not only with EF6.0 big different, and the EF core1.x also very different, also blame themselves, not to see the official documents, must go to find tutorials (most of the online tutorials are 1.x), hey, said many are tears.



The big guy pointed out that the method here is not the seed, to see the official document, the EF core does not have the seed method, so this time to add test data, not the seed.



Add an initialization data class named SeedData.cs


        public static class Seeddata

        {

            ///<summary>

            /// 

            ///configuration test Data

            /// 

            ///</summary> Public

            static void Initialize (IServiceProvider app)

            {

                var _dbcontext= app. Getrequiredservice<blogdbcontext> ();



                If there is already data, it returns if

                (_dbcontext.users.any ())

                {return

                    ;

                }

                    Add user test Data

                    _dbcontext.users.add (new user {UserName = "Niko", Password = "123"});



                    _dbcontext.savechanges ();



            }

        


Unlike the EF Core 1.x, 2.0 is added to the initialization method in the Main method in Program.cs (1.x is the Configure method in Startup.cs). Modify the Main method to:


            public static void Main (string[] args)

            {

                var host = Buildwebhost (args);

                using (var scope = host. Services.createscope ())

                {

                    var services = scope. serviceprovider;

                    Try

                    {

                        seeddata.initialize (services);

                    }

                    catch (Exception ex)

                    {

                        var logger = Services. Getrequiredservice<ilogger<program>> ();

                        Logger. Logerror (ex, "An error occurred seeding the DB");

                    }

                    Host. Run ();

            }


Next Update the database



Update-database-verbose



No problem, go to the database to view, the added seed data test data did not add in SQL profile does not monitor the add data operation. Add a breakpoint to the Main method, start IIS execution, step through, and discover that the seed test data is added to the database only when the program is running.


Related Article

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.