C# EF Core使用Scaffold-DbContext时,如何避免向数据库默认值列传递NULL值
Great question! You don't need to revert to manually creating domain models—there's a clean, maintainable fix that works with your frequent Scaffold-DbContext workflow, no changes to auto-generated code required.
Why the Error Happens
The issue is that EF Core explicitly sends a NULL value for the AuditApp column when inserting new records. Even though your database has a default constraint, SQL Server only applies that constraint when the column isn't included in the insert statement at all. Since the scaffolded entity includes AuditApp (which is null by default for new objects), EF Core passes that NULL to the database, triggering the "Cannot insert NULL" error.
The Fix: Extend DbContext with a Partial Class
EF Core's scaffolding tool generates the DbContext as a partial class, and includes a placeholder partial method OnModelCreatingPartial in the OnModelCreating logic. You can use this to add custom configuration without touching the auto-generated code.
Step 1: Create a Partial Configuration File
Make a new C# file in your My.Domain project (e.g., MyDbContext.AuditConfig.cs) and add this code:
using Microsoft.EntityFrameworkCore; using My.Domain.Models; public partial class MyDbContext { partial void OnModelCreatingPartial(ModelBuilder modelBuilder) { // Configure AuditApp to use database default on insert modelBuilder.Entity<PriceGroups>() .Property(p => p.AuditApp) .ValueGeneratedOnAdd() .HasDefaultValueSql("rtrim(isnull(app_name(),''))"); } }
What This Does
ValueGeneratedOnAdd()tells EF Core theAuditAppvalue is set by the database when a new record is created. This means EF Core will exclude the column from INSERT statements, letting the database apply its default constraint.HasDefaultValueSql()mirrors your database's exact default logic, ensuring consistency between EF Core's model understanding and the database schema.
Why This Works for Your Workflow
Since this is a partial class extension:
- The scaffolding tool will never overwrite this file—you can run
Scaffold-DbContextas often as needed without losing your configuration. - The auto-generated
MyDbContextautomatically callsOnModelCreatingPartialduring model setup, so your custom rules are applied every time.
No need to go back to manual model creation—this keeps your auto-generated code clean while solving the NULL insertion error.
内容的提问来源于stack exchange,提问作者Andrew

