8.1 KiB
Entity Framework Database-First Setup Guide
Project Structure
Your solution should follow this structure for optimal organization:
YourSolution/
├── src/
│ ├── YourProject/
│ │ ├── Controllers/
│ │ ├── Models/ <- Scaffolded models will go here
│ │ └── Data/ <- DbContext will go here
├── tests/
│ └── YourProject.Tests/
├── tools/
│ └── scaffold.bat <- Place scaffolding script here
└── YourSolution.sln
Alternative structure with scripts directory:
YourSolution/
├── src/
│ ├── YourProject/
│ │ ├── Controllers/
│ │ ├── Models/
│ │ └── Data/
├── tests/
│ └── YourProject.Tests/
├── scripts/
│ ├── database/
│ │ └── scaffold.bat <- Or place it here
│ └── other-scripts/
└── YourSolution.sln
To run the scaffold script:
Method 1 (From project directory):
- Open command prompt
- Navigate to project directory:
cd src/YourProject - Run:
../../tools/scaffold.bat
Method 2 (From any directory): Update your scaffold.bat to include the project path:
@echo off
cd ../src/YourProject
dotnet ef dbcontext scaffold ^
"Your_Connection_String" ^
Microsoft.EntityFrameworkCore.SqlServer ^
--project YourProject.csproj ^
[rest of your options]
pause
Note: Make sure your project has all required EF Core packages installed:
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.0" />
</ItemGroup>
This guide explains how to set up Entity Framework Core using a database-first approach for specific tables in the OnePlan database.
Prerequisites
Before starting, ensure you have:
- .NET SDK installed
- Entity Framework Core tools installed globally:
dotnet tool install --global dotnet-ef
- Required NuGet packages in your project:
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Scaffolding Process
Step 1: Create a Scaffold Script
Create a file named scaffold.bat in your tools directory with the following content:
@echo off
cd ../src/YourProject
dotnet ef dbcontext scaffold ^
"Server=your_server;Database=your_database;User=your_user;Password=your_password;TrustServerCertificate=True;Encrypt=True;" ^
Microsoft.EntityFrameworkCore.SqlServer ^
--project YourProject.csproj ^
--context-dir Data ^
--output-dir Models ^
--context OnePlanDbContext ^
--force ^
--data-annotations ^
--no-onconfiguring ^
--no-connection-string ^
-t fp.AddProviderEncountersDataForCharges ^
-t fp.AddProviderSummary ^
-t fp.AdjustmentChunkingConfiguration ^
-t fp.APEDepartmentWorkflowStatus ^
-t fp.APEWorkflow ^
-t fp.BenefitsSpreads ^
-t fp.BudgetConfig ^
-t fp.BudgetConfigDefaultSetting ^
-t fp.BudgetConfigSetting ^
-t fp.BudgetRefreshRequest ^
-t fp.BudgetRefreshRequestHistory ^
-t fp.ChargeVolumeAddProviderAdjustment ^
-t fp.ChargeVolumeSpreads ^
-t fp.DataRefreshTargetThreshold ^
-t fp.DepartmentChargeVolumeAdjustment ^
-t fp.DepartmentConfig ^
-t fp.DimCategory ^
-t fw.DimDepartment ^
-t dss.DimPhysician ^
-t fp.EngineLog ^
-t fp.EntityGroupConfig ^
-t fp.FixChangeHistoryRequest ^
-t fp.GeneralLedger ^
-t fp.GeneralLedgerInitialPlanConfigDetail ^
-t fp.GeneralLedgerSpreads ^
-t fp.InitialPlanRule ^
-t dbo.LOCK ^
-t dbo.log ^
-t dbo.OnePlanPerformanceTestHistory ^
-t fp.OnePlanPerformanceTestValidationResult ^
-t fp.PerformanceTestingSetting ^
-t fp.ProviderCompensationSpreads ^
-t fp.SamplingLog ^
-t fp.ScheduledRefreshRequest ^
-t fp.ServiceLineEncounterSpreads ^
-t fp.SettingCategory ^
-t fp.SpreadHistory ^
-t fp.StaffingInitialPlanConfigDetail ^
-t fp.StaffingSpreads ^
-t fp.StatisticsSpreads ^
-t fp.SystemSetting ^
-t dbo.TEScheduledTask ^
-t dbo.UserProfile ^
-t fp.viewBenefitsAdjustment ^
-t fp.viewDepartmentChargeVolumeAdjustment ^
-t fp.viewGeneralLedgerAdjustment ^
-t fp.viewReimbursementAdjustment ^
-t fp.viewReimbursementGeneralLedgerAdjustment ^
-t fp.viewServiceLineEncounterAdjustment ^
-t fp.viewStaffingAdjustment ^
-t fp.viewStatisticsAdjustment
pause
To run the scaffold script:
- Open command prompt
- Navigate to solution root directory
- Run:
tools/scaffold.bat
Note: Make sure your project has all required EF Core packages installed:
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.0" />
</ItemGroup>
Step 2: Configure Connection String
After scaffolding, configure your connection string in appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=your_server;Database=your_database;User=your_user;Password=your_password;TrustServerCertificate=True;Encrypt=True;"
}
}
Step 3: Configure DbContext
In your Program.cs or Startup.cs:
builder.Services.AddDbContext<OnePlanDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
Command Line Parameters Explained
--context-dir Data: Places the DbContext in a Data folder--output-dir Models: Places entity classes in a Models folder--force: Overwrites existing files--data-annotations: Uses attributes instead of fluent API--no-onconfiguring: Skips generating the OnConfiguring method--no-connection-string: Prevents connection string from being scaffolded into DbContext
Schema Organization
The tables are organized across multiple schemas:
fp: Financial Planning schema (majority of tables)dbo: Database Owner schemadss: Decision Support System schemafw: Framework schema
Best Practices
- Always scaffold all related tables together to maintain proper relationships
- Keep connection strings in configuration, not in code
- Use dependency injection for DbContext
- Consider using separate configuration classes for complex entity configurations
Troubleshooting
If you encounter SSL/TLS warnings, ensure your connection string includes:
TrustServerCertificate=TrueEncrypt=True
For Docker connections, use:
Server=localhost,1433(adjust port as needed)- Ensure the container is running and accessible
DbContext Organization
You have two main approaches for organizing your DbContext:
- Single DbContext (Recommended for this project)
public class OnePlanDbContext : DbContext
{
// All tables from all schemas
public DbSet<BudgetConfig> BudgetConfigs { get; set; }
public DbSet<DimDepartment> DimDepartments { get; set; }
// ... etc for all tables
}
Advantages:
- Simpler to manage
- All relationships maintained automatically
- Better for cross-schema transactions
- Easier to maintain data consistency
- Single dependency to inject
- Multiple DbContexts by Schema
public class FinancialPlanningDbContext : DbContext
{
// Only fp schema tables
public DbSet<BudgetConfig> BudgetConfigs { get; set; }
}
public class FrameworkDbContext : DbContext
{
// Only fw schema tables
public DbSet<DimDepartment> DimDepartments { get; set; }
}
Advantages:
- Better separation of concerns
- More focused contexts
- Can be more performant for specific schema operations
- Better for microservices architecture
For this project, the single DbContext approach is recommended due to:
- Highly interconnected tables
- Cross-schema queries
- Views joining data across schemas
- Coherent domain model around financial planning
Notes
- Views are included in the scaffold and will be read-only
- The scaffold includes all specified tables across multiple schemas
- Relationships between tables will be automatically mapped
- Generated models will be placed in the Models directory
- DbContext will be placed in the Data directory