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--
Editor to share with you how to use Entity Framework Core to generate database tables for Web projects. I hope you will get something after reading this article. Let's discuss it together.
I. introduction
In this article, we show you how to use EntityFrameworkCore in a Web project and generate database tables, taking ASP.NET Core WebApi as an example. Or adopt a hierarchical structure. The overall structure of the created project is shown in the following figure:
Project structure:
The EFCoreWeb.API:ASP.NET Core WebApi project, which provides Web functionality, references EFCoreWeb.Data in the project.
EFCoreWeb.Data: class library project, a class library based on .NET Core. The operations related to EFCore are stored.
EFCoreWeb.Model: class library project, a class library based on .NET Core. Entity classes are stored.
1. Add entity classes
We add the Student entity class to the EFCoreWeb.Model class library project:
Namespace EFCoreWeb.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
Because you want to use the Student entity class, you first need to add a reference to EFCoreWeb.Model in the EFCoreWeb.Data project.
Then add the Mircosoft.EntityFrameworkCore package to the EFCoreWeb.Data class library project and install it directly in NuGet:
Since we are using the SQLServer database, we also need to install the Microsoft.EntityFrameworkCore.sqlServer package, which is also installed directly in NuGet:
After installing the above two packages, add the Mapping folder in the EFCoreWeb.Data class library project to store the configuration files of Fluent API. The configuration partner class code of the Student class is as follows:
Using EFCoreWeb.Model;using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Metadata.Builders Namespace EFCoreWeb.Data.Mapping {/ Student configuration partner class, inherited from the Configure method in the IEntityTypeConfiguration generic interface / public class StudentMap: IEntityTypeConfiguration {/ implementation interface Used to configure the structure of the generated database table / public void Configure (EntityTypeBuilder builder) {/ / set the primary key builder.HasKey (p = > p.Id) / / set the generated table name builder.ToTable ("T_Student"); / / set the maximum length of the Name column builder.Property ("Name") .HasMaxLength (64); / / set the Name column to be a required builder.Property ("Name"). IsRequired ();}
Add a Context folder, and then add a data context class, inherited from DbContext:
Using EFCoreWeb.Model;using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Metadata.Builders Namespace EFCoreWeb.Data.Mapping {/ Student configuration partner class, inherited from the Configure method in the IEntityTypeConfiguration generic interface / public class StudentMap: IEntityTypeConfiguration {/ implementation interface Used to configure the structure of the generated database table / public void Configure (EntityTypeBuilder builder) {/ / set the primary key builder.HasKey (p = > p.Id) / / set the generated table name builder.ToTable ("T_Student"); / / set the maximum length of the Name column builder.Property ("Name") .HasMaxLength (64); / / set the Name column to be a required builder.Property ("Name"). IsRequired ();} II. Generate database tables
Here we use the package manager console migration to generate database tables. You need to install the Microsoft.EntityFrameworkCore.Tools package in the EFCoreWeb.Data project. Install Microsoft.EntityFrameworkCore.Tools and Microsoft.EntityFrameworkCore packages in the EFCoreWeb.API project. The EFCoreWeb.API project adds a reference to the EFCoreWeb.Data project.
First, add the database connection string to the appsettings.json file of the EFCoreWeb.API project:
{"Logging": {"LogLevel": {"Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information"}, "AllowedHosts": "*", "ConnectionString": {"DbConnection": "Data Source=.;Initial Catalog=EFTestDb;User ID=sa;Password=123456;"}}
Add a database connection to the ConfigureServices method of the Startup class:
Using EFCoreWeb.Data.Context;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.EntityFrameworkCore;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;namespace EFCoreWeb.API {public class Startup {public Startup (IConfiguration configuration) {Configuration = configuration;} public IConfiguration Configuration {get;} / / This method gets called by the runtime. Use this method to add services to the container. Public void ConfigureServices (IServiceCollection services) {# region database connection services.AddDbContext (options = > {/ / options.UseSqlServer (Configuration.GetConnectionString ("DbConnection")); options.UseSqlServer (Configuration.GetSection ("ConnectionString"). GetSection ("DbConnection") .value); # endregion services.AddControllers () } / / This method gets called by the runtime. Use this method to configure the HTTP request pipeline. Public void Configure (IApplicationBuilder app, IWebHostEnvironment env) {if (env.IsDevelopment ()) {app.UseDeveloperExceptionPage ();} app.UseRouting (); app.UseAuthorization (); app.UseEndpoints (endpoints = > {endpoints.MapControllers ();});}
After the configuration of the above steps is complete, start the migration in the package Manager console and add the migration using the following command:
Add-Migration Init
As shown in the following figure:
After the command is executed, the migration file is generated:
After adding the migration, execute the following command to update the database:
Update-Database
As shown in the following figure:
Check the database after execution:
As you can see, the length of the Name column in the table is generated according to the length set in the code, and it is not null, and the seed data is also inserted.
After reading this article, I believe you have a certain understanding of "how to use Entity Framework Core to generate database tables for Web projects". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!
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.