In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how Entity Framework Core uses the console program to generate database tables, which has a certain reference value, and interested friends can refer to it. I hope you will gain a lot after reading this article.
I. introduction
We use Code First to generate database tables. Let's first explain how to generate database tables in a console project.
In the previous article, we installed Mircosoft.EntityFrameworkCore directly in the console project, which we rarely use in real projects, using a hierarchical structure to put EF Core-related operations in a separate class library project, which we will explain in the following example. The project structure is shown in the following figure:
Project structure:
EFCoreTest.Con: the console project, which is used to run the program, and references EFCoreTest.Data in the project.
EFCoreTest.Data: class library project, based on .net Standard. What is stored is content related to EF Core.
EFCoreTest.Model: class library project, based on .net Standard. Stores the entity classes used in the project.
1. Add entity classes
Let's first add Student entities to the EFCoreTest.Model class library project:
Namespace EFCoreTest.Model {public class Student {public int Id {get; set;} public string Name {get; set;} public int Age {get; set;} public int Gender {get; set;}} 2, add Mircosoft.EntityFrameworkCore
We add the Mircosoft.EntityFrameworkCore package to the EFCoreTest.Data class library:
We use the SqlServer database, so we also install the Microsoft.EntityFrameworkCore.sqlServer package:
After the installation is complete, we add a reference to EFCoreTest.Model, and then add a data context class, which inherits from DbContext:
Using EFCoreTest.Model;using Microsoft.EntityFrameworkCore Namespace EFCoreTest.Data {/ data context class, inherited from DbContext / / public class EFCoreDbContext:DbContext {/ rewrite OnConfiguring method / protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder) {/ / using SqlServer database Pass the connection string optionsBuilder.UseSqlServer ("Data Source=." Initial Catalog=EFTestDb;User ID=sa;Password=123456; "); base.OnConfiguring (optionsBuilder) } / rewrite OnModelCreating, mainly do some configuration / for example, set the generated table name, primary key, character length / protected override void OnModelCreating (ModelBuilder modelBuilder) {/ / set the generated table name modelBuilder.Entity () .ToTable ("T_Student") / / set the Id field as the primary key modelBuilder.Entity (). HasKey (p = > p.Id) by default; / / set the maximum length of the Name field modelBuilder.Entity (). Property ("Name"). HasMaxLength (32); base.OnModelCreating (modelBuilder);} / / DbSet attribute public DbSet Students {get Set;}
After this work is done, we can use it to generate database tables.
Second, generate database tables
Let's generate database tables in three ways. First add a reference to EFCoreTest.Data in the console project.
1. Code generation
We can use code to generate the database so that the database can be generated automatically by calling the code that generates the database when the program starts. The code is as follows:
Using EFCoreTest.Data;using System;namespace EFCoreTest.Con {class Program {static void Main (string [] args) {Console.WriteLine ("Hello World!"); EFCoreDbContext dbContext = new EFCoreDbContext (); bool tfTrue = dbContext.Database.EnsureCreated (); if (tfTrue) {Console.WriteLine ("Database created successfully!") } else {Console.WriteLine ("database creation failed!");} Console.ReadKey ();}
Run the program:
The output result indicates that we have successfully created it. Go to the database and have a look:
We see that the database and table have been generated, and the field properties in the table are generated according to our settings in the code.
Note: if you go to generate the database when the program starts, it will report an error:
2. Package Manager console Migration
In addition to using code generation, we can also use the data migration command to generate database tables, which are divided into the following three steps.
1. Install the Microsoft.EntityFrameworkCore.tools package
To use the data migration command, you first need to install the Microsoft.EntityFrameworkCore.Tools package:
2. Add migration
First, add some seed data to the OnModelCreating () method of the data context class, so that after the database is generated, there is some basic data in the table:
Using EFCoreTest.Model;using Microsoft.EntityFrameworkCore Namespace EFCoreTest.Data {/ data context class, inherited from DbContext / / public class EFCoreDbContext:DbContext {/ rewrite OnConfiguring method / protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder) {/ / using SqlServer database Pass the connection string optionsBuilder.UseSqlServer ("Data Source=." Initial Catalog=EFTestDb;User ID=sa;Password=123456; "); base.OnConfiguring (optionsBuilder) } / rewrite OnModelCreating, mainly do some configuration / for example, set the generated table name, primary key, character length / protected override void OnModelCreating (ModelBuilder modelBuilder) {/ / set the generated table name modelBuilder.Entity () .ToTable ("T_Student") / / set the Id field as the primary key modelBuilder.Entity (). HasKey (p = > p.Id); / / set the maximum length of the Name field modelBuilder.Entity (). Property ("Name"). HasMaxLength (32); base.OnModelCreating (modelBuilder) / / add seed data modelBuilder.Entity () .HasData (new Student () {Id = 1, Name = "Tom", Age = 24, Gender = 1}) New Student () {Id = 2, Name = "Jack", Age = 23, Gender = 2}, new Student () {Id = 3 Name = "Kevin", Age = 26, Gender = 2}) } / / DbSet attribute public DbSet Students {get; set;}
Then use the following command to add the migration:
Add-Migration Initial
Add-Migration: is a migration command.
Initial: it can be understood as an alias for this migration. This name can be given at will, as long as you make sure that the name is not repeated during each migration.
As shown in the following figure:
Execute this command:
We see that the execution reported an error, and the error message indicates that the Mircosoft.EntityFrameworkCore.Tools package should also be installed in the startup item of our program. We install this package in the console program, and then execute the migration command:
As you can see, this implementation has been a success. A Migrations folder is generated after success, and there are two class files under this folder:
The 20200223132908_Init.cs file is a file generated from this migration, which records the changes that have taken place in this migration:
Using Microsoft.EntityFrameworkCore.Migrations Namespace EFCoreTest.Data.Migrations {public partial class Init: Migration {protected override void Up (MigrationBuilder migrationBuilder) {migrationBuilder.CreateTable (name: "T_Student", columns: table = > new {Id = table.Column (nullable: false) .Annotation ("SqlServer:Identity", "1") 1 "), Name = table.Column (maxLength: 32, nullable: true), Age = table.Column (nullable: false), Gender = table.Column (nullable: false)}, constraints: table = > {table.PrimaryKey (" PK_T_Student ", x = > x.Id) }); migrationBuilder.InsertData (table: "T_Student", columns: new [] {"Id", "Age", "Gender", "Name"}, values: new object [] {1,24,1, "Tom"}) MigrationBuilder.InsertData (table: "T_Student", columns: new [] {"Id", "Age", "Gender", "Name"}, values: new object [] {2,23,2, "Jack"}) MigrationBuilder.InsertData (table: "T_Student", columns: new [] {"Id", "Age", "Gender", "Name"}, values: new object [] {3,26,2, "Kevin"}) } protected override void Down (MigrationBuilder migrationBuilder) {migrationBuilder.DropTable (name: "T_Student");}
There are two ways to do this:
Up: this method is applied to the configuration of the database.
Down: this method is equivalent to a rollback operation. By executing this method, you can revert to the previous state.
One such file is generated for each migration.
The EFCoreDbContextModelSnapshot.cs is a file generated from the configuration in the OnModelCreating () method:
/ / using EFCoreTest.Data;using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Infrastructure;using Microsoft.EntityFrameworkCore.Metadata;using Microsoft.EntityFrameworkCore.Storage.ValueConversion Namespace EFCoreTest.Data.Migrations {[DbContext (typeof (EFCoreDbContext))] partial class EFCoreDbContextModelSnapshot: ModelSnapshot {protected override void BuildModel (ModelBuilder modelBuilder) {# pragma warning disable 612,618 modelBuilder .HasAnnotation ("ProductVersion", "3.1.2") .HasAnnotation ("Relational:MaxIdentifierLength", 128) .HasAnnotation ("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn) ModelBuilder.Entity ("EFCoreTest.Model.Student", b = > {b.Property ("Id") .ValueGeneratedOnAdd () .HasColumnType ("int") .HasAnnotation ("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn) B.Property ("Age") .HasColumnType ("int"); b.Property ("Gender") .HasColumnType ("int") B.Property ("Name") .HasColumnType ("nvarchar (32)") .HasMaxLength (32); b.HasKey ("Id"); b.ToTable ("T_Student") B.HasData (new {Id = 1, Age = 24, Gender = 1, Name = "Tom"}) New {Id = 2, Age = 23, Gender = 2, Name = "Jack"} New {Id = 3, Age = 26, Gender = 2, Name = "Kevin"}) }); # pragma warning restore 612,618}} 3. Update the database
After performing the above steps, we execute the command to update the database:
Update-Database
As shown in the following figure:
After successful execution, view the database data:
The Tstudy table has been generated, and there is added seed data in the table, so the migration is complete.
3. Command line migration
In addition to the above two methods, you can also use the command line for migration, which is commonly used in Web projects.
Use the following command to install:
Dotnet tool install-global dotnet-ef
As shown in the following figure:
After the installation is complete, we are executing the command:
Because my native version of the .NET SDK is 3.1.1, and the version of the dotent-ef I just installed is 3.1.2, which is incompatible, let's download the latest .NET SDK and install it.
Thank you for reading this article carefully. I hope the article "how to use the console program to generate database tables in Entity Framework Core" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.