增加一个不可以为Null的字段
- Step 1: Add the Column as Nullable (First PR & Deployment)
Modify the database schema to add the new column as nullable.
Update the application code to handle null values and assign a default before inserting data.
SQL Migration
ALTER TABLE MyTable ADD NewColumn INT NULL;
C# Code (Handling Nulls)
public class MyEntity
{
public int? NewColumn { get; set; } // Nullable field
}
// Ensure default value before inserting
int? newColumnValue = GetValueFromSource();
int finalValue = newColumnValue ?? 0; // Default to 0 if null
Deployment Considerations
✅ Deploy schema changes first
✅ Ensure application logic prevents NULL values from being inserted
✅ Monitor logs for unexpected behavior
- Step 2: Populate Existing Data (Second PR & Deployment)
Update existing records to ensure all rows have valid values before enforcing NOT NULL.
SQL Migration
UPDATE MyTable SET NewColumn = 0 WHERE NewColumn IS NULL;
Deployment Considerations
✅ Run data migration scripts in a controlled environment
✅ Validate that all rows have non-null values
✅ Monitor database performance
- Step 3: Enforce NOT NULL Constraint (Third PR & Deployment)
Once all records have valid values, alter the column to NOT NULL.
SQL Migration
ALTER TABLE MyTable ALTER COLUMN NewColumn INT NOT NULL;
Deployment Considerations
✅ Ensure all inserts provide a valid value
✅ Test thoroughly in staging before deploying
✅ Monitor for unexpected errors
- Step 4: Remove Null Handling Code (Fourth PR & Deployment)
Since the database now guarantees that the column will always have a value, remove unnecessary null checks.
C# Code (Before Removal)
int? newColumnValue = GetValueFromSource();
int finalValue = newColumnValue ?? 0; // Default to 0 if null
C# Code (After Removal)
int finalValue = GetValueFromSource(); // No need for null handling
Deployment Considerations
✅ Ensure all inserts provide a valid value
✅ Remove unnecessary default assignments
✅ Validate application behavior after deployment
- Best Practices
🔹 Use Feature Flags – Control rollout via feature flags if applicable
🔹 Monitor Logs & Errors – Track database changes and application behavior
🔹 Perform Incremental Rollouts – Deploy changes in small batches
🔹 Test in Staging First – Validate changes before production deployment