data First 在.netCore中运行

本文介绍如何在.NET Core环境中使用Mysql和SqlServer数据库进行数据First开发,包括安装必要包、生成数据库实体模型及配置数据库连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

data First 在.netCore中运行

1.安装几个引用文件

– Mysql数据库版本:

Install-Package MySql.Data.EntityFrameworkCore -Pre
Install-Package Pomelo.EntityFrameworkCore.MySql
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

–Sql Server数据库版本:

Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

----- Mysql数据库:

Scaffold-DbContext "server=.;userid=xxx;pwd=xxx;port=3306;database=xxx;sslmode=none;" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -Force

或者

Scaffold-DbContext "server=.;userid=xxx;pwd=xxx;port=3306;database=xxx;sslmode=none;" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -UseDatabaseNames -Force

– Sql Server数据库:

// Data Source填写登录数据库时候的服务器名称叭
Scaffold-DbContext "Data Source=DESKTOP-JFK9IBN;Initial Catalog=Blogging;User ID=sa;Password=123" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Force

解释:通过在nuget中获得的帮助

PM> get-help Scaffold-DbContext -detailed

名称
    Scaffold-DbContext
    
摘要
    Scaffolds a DbContext and entity types for a database.
    
    
语法
    Scaffold-DbContext [-Connection] <String> [-Provider] <String> [-OutputDir <String>] [-ContextDir <String>] [-Context <String>] [-Schemas <String[]>] [-Tables <String[]>] [-DataAnno
    tations] [-UseDatabaseNames] [-Force] [-NoOnConfiguring] [-Project <String>] [-StartupProject <String>] [-Namespace <String>] [-ContextNamespace <String>] [-NoPluralize] [-Args <Str
    ing>] [<CommonParameters>]
    
    
说明
    Scaffolds a DbContext and entity types for a database.
    

参数
    -Connection <String>
        The connection string to the database.
        
    -Provider <String>
        The provider to use. (E.g. Microsoft.EntityFrameworkCore.SqlServer)
        
    -OutputDir <String>
        The directory to put files in. Paths are relative to the project directory.
        
    -ContextDir <String>
        The directory to put the DbContext file in. Paths are relative to the project directory.
        
    -Context <String>
        The name of the DbContext. Defaults to the database name.
        
    -Schemas <String[]>
        The schemas of tables to generate entity types for.
        
    -Tables <String[]>
        The tables to generate entity types for.
        
    -DataAnnotations [<SwitchParameter>]
        Use attributes to configure the model (where possible). If omitted, only the fluent API is used.
        
    -UseDatabaseNames [<SwitchParameter>]
        Use table and column names directly from the database.
        
    -Force [<SwitchParameter>]
        Overwrite existing files.
        
    -NoOnConfiguring [<SwitchParameter>]
        Don't generate DbContext.OnConfiguring.
        
    -Project <String>
        The project to use.
        
    -StartupProject <String>
        The startup project to use. Defaults to the solution's startup project.
        
    -Namespace <String>
        The namespace to use. Matches the directory by default.
        
    -ContextNamespace <String>
        The namespace of the DbContext class. Matches the directory by default.
        
    -NoPluralize [<SwitchParameter>]
        Don't use the pluralizer.
        
    -Args <String>
        Arguments passed to the application.
        
    <CommonParameters>
        此 Cmdlet 支持常见参数: Verbose、Debug、
        ErrorAction、ErrorVariable、WarningAction、WarningVariable、
        OutBuffer、PipelineVariable 和 OutVariable。有关详细信息,请参阅
        about_CommonParameters (https:/go.microsoft.com/fwlink/?LinkID=113216)。
    
备注
    若要查看示例,请键入: "get-help Scaffold-DbContext -examples".
    有关详细信息,请键入: "get-help Scaffold-DbContext -detailed".
    若要获取技术信息,请键入: "get-help Scaffold-DbContext -full".
    有关在线帮助,请键入: "get-help Scaffold-DbContext -online"

接下来配置有两种方法

1.在Startup类中添加并读取配置文件中连接字符串

 public void ConfigureServices(IServiceCollection services)
        {
           string connectString = Configuration.GetConnectionString("ConnectString");//读取连接字符串
            services.AddDbContext<公司Context>(options =>options.UseSqlServer(connectString));	//添加中间件并连接字符串
            services.AddControllersWithViews();
        }
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "ConnectString": "Server=192.168.1.3;Initial Catalog=公司;User ID=vcl_elec_com;Password=QAZ123PLM,.!@#;Trusted_Connection=False;MultipleActiveResultSets=true"
  }

2.在Startup类中添加中间件

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<公司Context>();	//添加中间件并连接字符串
            services.AddControllersWithViews();
        }

在上下文context中添加连接字符串

 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 {
     if (!optionsBuilder.IsConfigured)
     {
         //连接字符串
         optionsBuilder.UseSqlServer("Data Source=192.168.1.3;Initial Catalog=公司;User ID=vcl_elec_com;Password=123456");
     }
 }

在controller中调用,需要构造函数注入–搞定

private readonly 公司Context context;
public HomeController(公司Context context)
{
    _logger = logger;
    this.context = context;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值