EF Core 2.0 uses Mssql/mysql for DB first and code first

Source: Internet
Author: User
Tags mssql

Reference address

Entity Framework Official website

ASP. NET core MVC and EF Core-tutorial Series

Environment

Visual Studio 2017

Latest version of the. NET Core 2.0 SDK

Latest version of Windows PowerShell

Start building

1. Create a new project in Visual Studio 2017

    • "file" > "New" > "Project"
    • Choose Installed > Templates > Visual C # >. NET Core from the left menu.
    • select "ASP. NET Core Web application".
    • enter "EFGetStarted.AspNetCore.NewDb" as the name, then click OK.
    • in "New ASP. NET Core Web Application dialog box:
      • Make sure the drop-down list is selected. NET core and ASP. 2.0
      • select "Web application ( Model View Controller) "project template
      • Make sure" Authentication "is set to" No Authentication "
      • Click OK

2. Install the Entity Framework Core

    • Tools > NuGet Package Manager > Package Manager console

1.1. Installing the database Provider

MSSQL Run

Install-package Microsoft.EntityFrameworkCore.SqlServer

MySQL Run

Grapefruit: Install-package POMELO.ENTITYFRAMEWORKCORE.MYSQL
Or
Official: Install-package mysql.data.entityframeworkcore-version 8.0.11

1.2. install the Package Manager console
Run: Install-package Microsoft.EntityFrameworkCore.Tools

1.3. Installation Design Package
Run: Install-package Microsoft.EntityFrameworkCore.Design

Data Base provides program design time package (EF Core 2.0 no longer required )
MSSQL Run: Install-package Microsoft.EntityFrameworkCore.SqlServer.Design
MYSQL Run: Install-package Pomelo.EntityFrameworkCore.MySql.Design

DB first--Creating a model from an existing database

MySQL Run

Scaffold-dbcontext-connection "Server=localhost; User Id=root; PASSWORD=123456;DATABASE=VANFJ "-provider" POMELO.ENTITYFRAMEWORKCORE.MYSQL "-outputdir" Models "

MSSQL Run

Scaffold-dbcontext-connection "Server=localhost; User Id=root; PASSWORD=123456;DATABASE=VANFJ "-provider" Microsoft.EntityFrameworkCore.SqlServer "-outputdir" Models "

Usage Note: Replace the connection string in connection with your own database connection, replacing models in OutputDir with the file directory name you want to generate

Code first--from model generation to database

1. Create a model

1.1. Create Schoolcontext context

 Public classschoolcontext:dbcontext{ PublicSchoolcontext (dbcontextoptions<schoolcontext> options):Base(options) {} PublicDbset<course> Courses {Get;Set; } Publicdbset<enrollment> Enrollments {Get;Set; } PublicDbset<student> Students {Get;Set; }protected Override voidonmodelcreating (ModelBuilder ModelBuilder) {modelbuilder.entity<Course> (). ToTable ("Course"); Modelbuilder.entity<Enrollment> (). ToTable ("Enrollment"); Modelbuilder.entity<Student> (). ToTable ("Student");}} Public classstudent{ Public intID {Get;Set; } Public stringLastName {Get;Set; } Public stringFirstmidname {Get;Set; } PublicDateTime EnrollmentDate {Get;Set; } Publicicollection<enrollment> Enrollments {Get;Set; }} Public enumGrade {A, B, C, D, F} Public classenrollment{ Public intEnrollmentid {Get;Set; } Public intCourseID {Get;Set; } Public intStudentID {Get;Set; } PublicGrade? Grade {Get;Set; } PublicCourse Course {Get;Set; } PublicStudent Student {Get;Set; }} {A, B, C, D, F} Public classenrollment{ Public intEnrollmentid {Get;Set; } Public intCourseID {Get;Set; } Public intStudentID {Get;Set; } PublicGrade? Grade {Get;Set; } PublicCourse Course {Get;Set; } PublicStudent Student {Get;Set; }} Public classcourse{[databasegenerated (databasegeneratedoption.none)] Public intCourseID {Get;Set; } Public stringTitle {Get;Set; } Public intCredits {Get;Set; } Publicicollection<enrollment> Enrollments {Get;Set; }}
View Code

1.2. startup file Injection Context

EF Core in version 2.0, a new way to register custom DbContext types in dependency injection is to introduce a pool of reusable DbContext instances in a transparent manner.
To use the DbContext pool, use Adddbcontextpool instead of Adddbcontext during service registration

 Public void configureservices (iservicecollection services) {services. Adddbcontextpool<SchoolContext> (Options andoptions). Usemysql (configuration.getconnectionstring ("defaultconnection"=  = Newtonsoft.Json.ReferenceLoopHandling.Ignore);}
View Code

1.3. Add a connection string to the Appsettings.json file

{"ConnectionStrings": {"defaultconnection":"Server=localhost; User Id=root; PASSWORD=123456;DATABASE=VANFJ"},"Logging": {"Includescopes":false,"LogLevel": {"Default":"Warning"}}}
View Code

2. Execute the nuget command to create the database

Building Scaffolding for migrations

Run: add-migration initialcreate

Apply a new migration to a database

Run: Update-database

EF Core 2.0 nuget command

Get-help about_entityframeworkcore Get EF Core command Help

Add a migration database to migrate the name directory (and its child namespace) path is relative to the project directory. The default value is "migrations".
Add-migration-name <String>-outputdir <String>
Add-migration Initialcreate The first time to perform initialization with this

Deleting the last Migration database does not check to see if the migration has been applied to the database.
Remove-migration-force

Target migration. If "0", all migrations will be resumed. Default to the last migration.
Update-database
Update-database lastgoodmigration Restore Migration

The database displayed by the delete database is discarded, but it is not deleted
Drop-database-whatif

Get-dbcontext getting information about the DbContext type

Updating DbContext and entity types from a database
Scaffold-dbcontext
-connection <String> Database connection string.
-provider <String> the provider to use. (e.g. Microsoft.EntityFrameworkCore.SqlServer)
-outputdir <string > The directory where you want to put the file. The path is relative to the project directory.
--context <string > to generate the DbContext name.
-schemas <String[]> to generate the table schema for the entity type.
-tables <String[]> the table to generate the entity type for.
-dataannotations uses properties to configure the model, if possible. If omitted, only the fluent API is used.
-usedatabasenames is used directly from database tables and column names.
-force Overwrite existing files.

SQL scripts generated from the migration
Script-migration
-from <String> start migration. Default value is 0 (initial database)
-to <String> end of migration. Default to Last Migration
-idempotent generate scripts that can be used in any migrated database
-output <String> files to write the results to

EF Core 2.0 uses Mssql/mysql for DB first and code first

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.