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         }
  • 相关阅读:
    Java集合:HashMap底层实现和原理(源码解析)
    Java获取异常堆栈信息
    win7 64位系统 PB连接oracle数据库出现“oracle library oci.dll could not be loaded”问题的解决方法
    Oralce 使用递归方式获取BOM树显示结构
    Oracle 链接数据库语句
    根据数据窗口某列的值定位行
    pb中数据窗口filter函数和retrieve函数的区别和联系
    用代码保存共享文件夹登录名和密码
    PB 组合数据窗口子窗口数据赋值方法
    PB 导出PDF
  • 原文地址:https://www.cnblogs.com/fanqisoft/p/10809938.html
Copyright © 2011-2022 走看看