You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# EF Core使用Scaffold-DbContext时,如何避免向数据库默认值列传递NULL值

Solution: Let EF Core Use Database Default Without Modifying Scaffolded Code

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 the AuditApp value 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-DbContext as often as needed without losing your configuration.
  • The auto-generated MyDbContext automatically calls OnModelCreatingPartial during 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 06:14:11