如何将‘Update Model from Database’设为构建步骤,自动更新.edmx文件?
Absolutely! You can absolutely automate EDMX regeneration as part of your build process—no more tedious manual wizard runs every time your database schema gets updated. Here are the most practical, battle-tested ways to set this up:
1. Custom MSBuild Targets (Best for Visual Studio Integration)
This approach ties directly into your project's build pipeline, so it runs seamlessly alongside your regular compile steps.
Step 1: Edit Your Project File
Right-click your project in Solution Explorer → Unload Project, then right-click again and select Edit [YourProjectName].csproj. Add this custom target right before the closing </Project> tag:
<Target Name="UpdateEdmxFromDatabase" BeforeTargets="Build"> <PropertyGroup> <!-- Replace these with your actual project details --> <EdmxFilePath>Models/YourDatabaseModel.edmx</EdmxFilePath> <DbConnectionString>Data Source=YOUR_SERVER_NAME;Initial Catalog=YOUR_DB_NAME;Integrated Security=True;</DbConnectionString> <DbProvider>System.Data.SqlClient</DbProvider> </PropertyGroup> <!-- Uses Entity Framework Power Tools command-line utility --> <Exec Command=""$(DevEnvDir)../Common7/IDE/EntityFrameworkPowerTools.exe" /updateedmx "$(ProjectDir)$(EdmxFilePath)" /connectionstring "$(DbConnectionString)" /providername "$(DbProvider)"" /> </Target>
Note: If you don’t have Entity Framework Power Tools installed, grab it from the Visual Studio Extension Marketplace—it’s free and essential for this workflow.
Step 2: Tune When It Runs
If you don’t want this to fire every single build (since it adds a bit of overhead), add a condition to limit it to specific configurations (like Debug only):
<Target Name="UpdateEdmxFromDatabase" BeforeTargets="Build" Condition="'$(Configuration)' == 'Debug'"> <!-- Keep the rest of the target content here --> </Target>
2. PowerShell Script + Pre-Build Event
For more flexibility (like adding custom logic or logging), a PowerShell script hooked into a pre-build event works great.
Step 1: Write the Update Script
Create a file named UpdateEdmx.ps1 in your project root with this code:
param( [string]$EdmxPath, [string]$ConnectionString, [string]$ProviderName ) # Load Visual Studio's EF design assemblies (adjust path to match your VS version) $vsPath = "C:\Program Files (x86)\Microsoft Visual Studio\2022\Community\Common7\IDE\PublicAssemblies\" Add-Type -Path "$vsPath\Microsoft.Data.Entity.Design.dll" Add-Type -Path "$vsPath\Microsoft.Data.Entity.Design.UI.dll" # Initialize the model updater and sync with the database $modelUpdater = New-Object Microsoft.Data.Entity.Design.VisualStudio.ModelUpdates.ModelUpdater $modelUpdater.UpdateModelFromDatabase($EdmxPath, $ConnectionString, $ProviderName, $true, $true) Write-Host "✅ EDMX file updated successfully from database schema!"
Make sure to update the $vsPath to match your Visual Studio version (2019, 2022) and edition (Community/Professional/Enterprise).
Step 2: Link to Pre-Build Event
Go to your project properties → Build Events → Pre-build event command line, and paste this (adjust paths as needed):
powershell -ExecutionPolicy Bypass -File "$(ProjectDir)UpdateEdmx.ps1" -EdmxPath "$(ProjectDir)Models/YourDatabaseModel.edmx" -ConnectionString "Data Source=YOUR_SERVER_NAME;Initial Catalog=YOUR_DB_NAME;Integrated Security=True;" -ProviderName "System.Data.SqlClient"
Key Things to Keep in Mind
- Build Speed: Regenerating EDMX on every build adds time. Use configuration conditions or a separate MSBuild target (run manually with
msbuild /t:UpdateEdmxFromDatabase) to balance automation and speed. - Secure Connection Strings: Avoid hardcoding credentials! Use project properties, environment variables, or secure configuration files to store connection strings.
- Version Control: Make sure your EDMX file is checked into Git (or your VCS of choice). Automated updates will modify the file, so you’ll want to track those changes alongside your database schema updates.
- Tool Compatibility: Double-check that your EF version (EF6 vs. older) and Visual Studio edition are compatible with the tools you’re using.
内容的提问来源于stack exchange,提问作者gillzj00

