ASP. NET core uses EF7 Code first to create a database, while using commands to create a database (the data migration was not successful, only the title can be made this.) )

Source: Internet
Author: User
Tags dotnet postgresql

1. First download the vs2015 ASP (RC2) plug-in tool (Https://www.microsoft.com/net/core#windows)
2. Create an ASP. Project, here I create a simple project, is a console, on this basis I am ready to build a project of ASP.

3. Add dependent dependencies (MVC dependencies and EF dependencies) in Projecr.json:

{"Dependencies": {"Microsoft.NETCore.App": {"version": "1.0.0-rc2-3002702", "type": "Platform"}, " Microsoft.AspNetCore.Server.IISIntegration ":" 1.0.0-rc2-final "," Microsoft.AspNetCore.Server.Kestrel ":" 1.0.0-    Rc2-final "," Microsoft.AspNetCore.StaticFiles ":" 1.0.0-rc2-final "," MICROSOFT.ASPNETCORE.MVC ":" 1.0.0-rc2-final ", "Microsoft.AspNetCore.Razor.Tools": {"version": "1.0.0-preview1-final", "type": "Build"}, "Npgsql.entit Yframeworkcore.postgresql ":" 1.0.0-rc2-release1 "," Microsoft.EntityFrameworkCore.Tools ": {" version ":" 1.0.0-previ    Ew1-final "," type ":" Build "}," Microsoft.Extensions.Configuration.EnvironmentVariables ":" 1.0.0-rc2-final ", "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final", "Microsoft.Extensions.Logging": "1.0.0-rc2-final", "  Microsoft.Extensions.Logging.Console ":" 1.0.0-rc2-final "," Microsoft.Extensions.Logging.Debug ":" 1.0.0-rc2-final " }, "Tools": {"Microsoft.aspnetcorE.razor.tools ": {" version ":" 1.0.0-preview1-final "," Imports ":" Portable-net45+win8+dnxcore50 "}," Micros Oft. AspNetCore.Server.IISIntegration.Tools ": {" version ":" 1.0.0-preview1-final "," Imports ":" Portable-net45+win8+dn        Xcore50 "}," Microsoft.EntityFrameworkCore.Tools ": {" version ":" 1.0.0-preview1-final "," Imports ": [      "Portable-net45+win8+dnxcore50", "Portable-net45+win8"]}}, "Frameworks": {"netcoreapp1.0": {    "Imports": ["dotnet5.6", "Dnxcore50", "Portable-net45+win8"]}}, "Buildoptions": { "Emitentrypoint": True, "Preservecompilationcontext": true}, "Runtimeoptions": {"Gcserver": true}, "Publishop  tions ": {" include ": [" Wwwroot "," web. config "]}," scripts ": {" postpublish ": [" Dotnet Publish-iis --publish-folder%publish:outputpath%--framework%publish:fulltargetframework% "]}}

4. Make the following changes in the Startup.cs file:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;usingMicrosoft.AspNetCore.Builder;usingMicrosoft.AspNetCore.Hosting;usingMicrosoft.AspNetCore.Http;usingMicrosoft.Extensions.DependencyInjection;usingMicrosoft.Extensions.Configuration;usingMicrosoft.Extensions.Logging;namespacesmblog{ Public classStartup { PublicStartup (ihostingenvironment env) {varBuilder =NewConfigurationbuilder (). Setbasepath (env. Contentrootpath). Addjsonfile ("Appsettings.json", Optional:true, Reloadonchange:true)               . Addjsonfile ($"appsettings. {env. Environmentname}.json", Optional:true); if(env. Isdevelopment ()) {} builder.            Addenvironmentvariables (); Configuration=Builder.        Build (); }         PublicIconfigurationroot Configuration {Get; }  Public voidconfigureservices (iservicecollection services) {services.        Addmvc (); }        //This method gets called by the runtime. Use this method to configure the HTTP request pipeline.         Public voidConfigure (Iapplicationbuilder app, Ihostingenvironment env, iloggerfactory loggerfactory) {Loggerf Actory. Addconsole (Configuration.getsection ("Logging"));            Loggerfactory.adddebug (); App.            Usestaticfiles (); App. USEMVC (Routes={routes. MapRoute (Name:"default", Template:"{controller=home}/{action=index}/{id?}");        }            ); }    }}

Now there is no service to add EF.

5. Create a new Appsettings.json file for project-related configuration, log configuration in Startup.cs, and subsequent configuration of the EF database in this file.

{"  ConnectionStrings": {    "PostgreSql": "User id=postgres; password=123456; Host=localhost; Port=5432;database=smbloh "  },  " Logging ": {    " includescopes ": false,    " LogLevel ": {      " Default " : "Debug",      "System": "Information", "      Microsoft": "Information"}}  }

6. Create a new view of HomeController and Index action and index for testing, as shown in the project directory structure in MVC5. Controllers and views and models files.

7. Run over dotnet (dotnet equivalent to previous DNX) See this result to show that the MVC6 project is completed

8. Start the EF operation. Create a new entity in models article simply give him three fields.

     Public class article    {        publicintsetget;}          Public string Set Get ; }          Public string Set Get ; }    }

9. Create a new Smcontext (EF context object) code in models as follows:

 Public class Smcontext:dbcontext    {        publicbase(option)        {        }        publicset  Get;}         protected Override void onmodelcreating (ModelBuilder ModelBuilder)        {            base. Onmodelcreating (ModelBuilder);        }    }

10. Modify the Startup.cs file. Increase support for EF: The code is as follows

      Public void configureservices (iservicecollection services)        {            services. Addmvc ();            Services. Adddbcontext<SMContext> (option = option). Usenpgsql (configuration.getconnectionstring ("PostgreSql")));        

11. In order to initialize the database, create a new Sampledata class here, call this class when the project is started, and initialize the database. The code is as follows:

namespacesmblog.models{ Public classSampleData { Public Async StaticTask initdb (IServiceProvider service) {vardb = service. Getservice<smcontext>(); if(Db. Database! =NULL&&db. Database.ensurecreated ()) {article Article=NewArticle {Title="Test", Description="Smblog Test"                }; Db.                Articles.add (article); awaitdb.            Savechangesasync (); }        }    }}

This place is more flexible, we can insert a piece of data when we initialize the database, or we can not insert it. I inserted a piece of data in this place. Of course there are users in the system, the insertion of the administrator is more appropriate operation.

12. Modify the startup file again to call SampleData to create the database and initialize it when the project is loaded. The code is as follows:

   Public Async voidConfigure (Iapplicationbuilder app, Ihostingenvironment env, iloggerfactory loggerfactory) {Loggerf Actory. Addconsole (Configuration.getsection ("Logging"));            Loggerfactory.adddebug (); App.            Usestaticfiles (); App. USEMVC (Routes={routes. MapRoute (Name:"default", Template:"{controller=home}/{action=index}/{id?}");            }            ); await sampledata.initdb (app.        ApplicationServices); }

13. Start the project again, my data has been created successfully, and a piece of data is inserted.

14. Database migration. When we add a user entity and modify the article entity, it is time to migrate the database, rather than simply re-establish the database deletion. To ensure that the original data is unchanged, modify the database structure.

The added user entity is as follows:

     Public class User    {        publicintsetget;}          Public string Set Get ; }          Public string Set Get ; }    }

The modified article entity is as follows, adding a createtime field

    Public classArticle { Public intId {Set;Get; }  Public stringTitle {Set;Get; }  Public stringDescription {Set;Get; }  Public stringLabel {Set; Get; }
}

In the Smcontext file, increase the user's dbconetxt;

The following code:

         Public Set get; }

15. PM command input in vs Add-migration Newbook

When successful, a migrations folder is generated in the project. There's a snapshot file and a migrated file. Not expanded here.

In the execution command: update-database Newbook found an error.

Baidu has n times or not, only the original database is deleted again this command can be executed, so the words are not to realize the real migration of data.

The failure ended today. It's not too early to go to bed. Not good welcome not to shoot bricks, at the same time very urgent someone to solve my problem.

 Public void Configureservices (iservicecollection services) {services.        Addmvc (); Services. adddbcontext<smcontext> (option = option). Usenpgsql (Configuration.    GetConnectionString ("POSTGRESQL")); }

ASP. NET core uses EF7 Code first to create a database, while using commands to create a database (the data migration was not successful, only the title can be made this.) )

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.