本文共 2797 字,大约阅读时间需要 9 分钟。
在 Entity Framework Core 开发中,DB First 和 Code First 是两种常用的数据绑定模式。这种指南将详细介绍这两种模式的安装、配置以及常用操作。
DB First 是基于数据库架构生成 DbContext 及实体类型的过程。这种模式适合从现有数据库迁移为代码,或者作为代码生成的基础。
使用 .NET Core CLI 安装必要工具:
dotnet tool install --global dotnet-efdotnet add package Microsoft.EntityFrameworkCore.Design
安装对应数据库的 provider:
dotnet add package Pomelo.EntityFrameworkCore.MySql --version 5.0.0-alpha.2
使用 CLI 生成代码:
dotnet ef dbcontext scaffold "Server=localhost;Uid=root;Pwd=123456;Database=databaseName" Pomelo.EntityFrameworkCore.MySql
Code First 是基于 DbContext 和 实体类型生成数据库架构的过程。这种模式适合从代码开始,逐步创建数据库。
同样安装必要工具:
dotnet tool install --global dotnet-efdotnet add package Microsoft.EntityFrameworkCore.Design
安装对应数据库的 provider:
dotnet add package Pomelo.EntityFrameworkCore.MySql --version 5.0.0-alpha.2
定义 DbContext 和 实体类:
using System.Collections.Generic;using Microsoft.EntityFrameworkCore;namespace EFGetStarted{ public class BloggingContext : DbContext { public DbSet Blogs { get; set; } public DbSet Posts { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder options) => options.UseSqlite("Data Source=blogging.db"); } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List Posts { get; set; } = new(); } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } }} 生成初始迁移并应用:
dotnet ef migrations add InitialCreatedotnet ef database update
在属性字段变更时,更新数据库结构:
dotnet ef migrations removedotnet ef database update
dotnet ef dbcontext 参数说明以下是 dotnet ef dbcontext 命令的常用参数:
| 选项 | 简写 | 说明 |
|---|---|---|
--data-annotations | -d | 使用属性可在可能的架构中配置模型(默认使用 Fluent API) |
--context | -c | 生成的 DbContext 类名称 |
--context-dir | DbContext 类所在目录 | |
--context-namespace | 生成的 DbContext 命名空间 | |
--force | -f | 覆盖现有文件 |
--output-dir | -o | 输出文件的目录 |
--namespace | -n | 所有生成类的命名空间 |
--schema | 需要生成的架构 | |
--table | -t | 需要生成的表 |
--use-database-names | 使用数据库中的表和列名称 | |
--no-onconfiguring | 禁止生成 OnConfiguring 方法 | |
--no-pluralize | 不使用复数化程序 |
用于为 DbContext 生成数据库和实体类型的命令:
| 参数 | 说明 |
|---|---|
-connection | 数据库连接字符串 |
-provider | 数据库提供程序名称 |
-output-dir | 输出文件的目录 |
-context-dir | DbContext 类所在目录 |
-namespace | 生成类的命名空间 |
-context | 生成的 DbContext 类名称 |
-schema | 需要生成的架构 |
-table | 需要生成的表 |
--data-annotations | 使用属性配置模型 |
--use-database-names | 使用数据库中的表和列名称 |
--force | 覆盖现有文件 |
--no-onconfiguring | 禁止生成 OnConfiguring 方法 |
--no-pluralize | 不使用复数化程序 |
通过以上命令,可以轻松地在项目中配置和使用 EF Core 的数据库绑定功能。
转载地址:http://oqlyz.baihongyu.com/