gpt4 book ai didi

entity-framework-core - 如何在 Entity Framework 核心中删除生成的模型类

转载 作者:行者123 更新时间:2023-12-04 17:29:48 24 4
gpt4 key购买 nike

我们正在使用 EF 核心,我们遵循数据库优先的方法。

我们正在使用 Scaffold-DbContext用于更新我们的上下文文件。现在,我们正在清理,目前我们的数据库中有一些表已被删除,当我们运行时 Scaffold-DbContext针对 DB,通过删除所有已删除的表(模型类)引用来更新我的上下文文件

但是在Model文件夹下,我们仍然看到我们删除的表Model类文件存在。

关于如何删除它们而不是手动的任何输入?

最佳答案

Scaffold-DbContext 不支持自动删除未使用的类(对应于重命名或删除的表的类)。您必须以其他方式删除这些文件。在 Windows 上,您可以通过在 之后运行此命令来自动化该过程。成功 脚手架。

PowerShell -Command "& {Get-ChildItem -path "Model" | where {$_.LastWriteTime -lt (date).AddMinutes(-1)} | Remove-Item}"
工作原理:Scaffold-DbContext 重新生成所有文件,因此即使它们的内容保持不变,它们的日期/时间也会发生变化。孤立文件将保留较旧的日期/时间。该命令使用 PowerShell 删除超过一分钟的文件。这已经足够了,因为通常您在一分钟内不会多次运行脚手架,而且通常脚手架运行时间不到一分钟。在其他操作系统上使用类似的 shell 命令。
重要提示:生成的文件必须在一个子目录中(在本例中为 Model)并且该子目录中不能有其他文件,否则它们将被删除!
完整示例:我最终使用了一个名为 Update from database.cmd 的脚本在 Windows 上:
@echo off
rem Change current directory to the one containing this script.
cd /D "%~dp0"

rem Restore local command "dotnet ef". Init local commands before that. See .config\dotnet-tools.json.
dotnet tool restore

rem Generate files in a subdirectory called "Model".
dotnet ef dbcontext scaffold "Data Source=...;Database=..." Microsoft.EntityFrameworkCore.SqlServer --output-dir Model --force --context MyDbContext

rem Don't run cleanup if build failed or else all generated files will be deleted!
if %errorlevel% neq 0 goto end

rem Cleanup: delete orphaned files from "Model" subdirectory.
PowerShell -Command "& {Get-ChildItem -path "Model" | where {$_.LastWriteTime -lt (date).AddMinutes(-1)} | Remove-Item}"

:end
rem Inspect console output.
pause

关于entity-framework-core - 如何在 Entity Framework 核心中删除生成的模型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60809025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com