zoukankan      html  css  js  c++  java
  • ASP.NET Core中使用EF Core(MySql)Database First

    ⒈创建数据库,在数据中执行以下脚本。

     1 CREATE DATABASE Blogging;
     2 
     3 USE Blogging;
     4 
     5 CREATE TABLE Blog (
     6     BlogId int not null PRIMARY key auto_increment,
     7     Url text not null
     8 );
     9 
    10 CREATE TABLE Post (
    11     PostId int NOT NULL PRIMARY key auto_increment,
    12     BlogId int NOT NULL,
    13     Content text,
    14     Title varchar(100),
    15     CONSTRAINT FK_Post_Blog_BlogId FOREIGN KEY(BlogId) REFERENCES Blog(BlogId) ON DELETE CASCADE
    16 );
    17 
    18 INSERT INTO Blog (Url) VALUES
    19 ('http://blogs.msdn.com/dotnet'),
    20 ('http://blogs.msdn.com/webdev'),
    21 ('http://blogs.msdn.com/visualstudio')

    ⒉添加依赖

      MySql.Data.EntityFrameworkCore

    实施反向工程,基于现有数据库创建数据表实体类及上下文。

      第一种方式:"Visual Studio 2019" >“工具”>“NuGet 包管理器”>“程序包管理器控制台”,执行以下命令(最好提前编译以下项目,否则以下命令可能执行不成功)

    1 #Scaffold-DbContext "数据库连接字符串" 数据库提供程序 -OutputDir 输出文件夹
    2 Scaffold-DbContext "server=localhost;port=3306;database=blogging;user=root;password=admin;" MySql.Data.EntityFrameworkCore -OutputDir Models

      第二种方式:使用.Net Core CLI,执行以下命令

    1 #dotnet ef dbcontext scaffold "数据库连接字符串" 数据库提供程序 -o 输出文件夹
    2 dotnet ef dbcontext scaffold "server=localhost;port=3306;database=blogging;user=root;password=admin;" MySql.Data.EntityFrameworkCore -o Models

    ⒋使用依赖注入将上下文注册为服务

     1 public void ConfigureServices(IServiceCollection services)
     2         {
     3             services.Configure<CookiePolicyOptions>(options =>
     4             {
     5                 // This lambda determines whether user consent for non-essential cookies is needed for a given request.
     6                 options.CheckConsentNeeded = context => true;
     7                 options.MinimumSameSitePolicy = SameSiteMode.None;
     8             });
     9 
    10 
    11             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    12 
    13             var connection = Configuration["ConnectionStrings:MySqlConnection"];
    14 
    15             services.AddDbContext<BloggingDbContext>(options =>
    16             {
    17                 options.UseMySQL(connection);
    18             });
    19         }
  • 相关阅读:
    在 Windows 上测试 Redis Cluster的集群填坑笔记
    vmware安装黑苹果教程
    微信支付v3发布到iis时的证书问题
    Linux下安装SQL Server 2016(连接篇SQL Server on linux)
    Linux下安装SQL Server 2016(连接篇SQL Server on linux)
    Linux下安装SQL Server 2016(安装篇SQL Server on linux)
    Linux下安装SQL Server 2016(准备篇SQL Server on linux)
    客服端与服务端APP支付宝支付接口联调的那些坑
    ASP.NET MVC]WebAPI应用支持HTTPS的经验总结
    .net平台下C#socket通信(中)
  • 原文地址:https://www.cnblogs.com/fanqisoft/p/10809938.html
Copyright © 2011-2022 走看看