Fixing the "String or Binary Data Would Be Truncated" Error in EF Core
If you’ve worked with Entity Framework Core and SQL Server, you’ve likely encountered this error:
String or binary data would be truncated
At first glance, this error is frustrating because it doesn't tell you:
- Which table failed
- Which column caused the issue
- What the allowed size is
- What value exceeded the limit
So debugging becomes time-consuming.
The Problem
Consider this table:
Users
FirstName VARCHAR(20)
Now insert:
"ThisIsAVeryLongNameThatExceedsLimit"
SQL Server throws:
String or binary data would be truncated
But gives no details.
The Solution: DBGuard
To solve this, I built a library called DBGuard.
DBGuard validates entity data against the actual database schema before SaveChanges.
How It Works
Flow:
Application
→ EF Core SaveChanges
→ DBGuard Interceptor
→ Validation Engine
→ Database
Example
Instead of SQL Server error:
String or binary data would be truncated
DBGuard returns:
DBGuard Validation Failed
Table: Users
Column: FirstName
Allowed Length: 20
Actual Length: 45
Suggestion: Trim input or increase column length
Installation
dotnet add package DBGuard
Usage
builder.Services.AddDbGuard(connectionString);
builder.Services.AddDbContext<AppDbContext>((sp, options) =>
{
var interceptor = sp.GetRequiredService<DbGuardInterceptor>();
options.UseSqlServer(connectionString)
.AddInterceptors(interceptor);
});
Features
- Schema-aware validation
- Column length validation
- Null & type validation
- Decimal precision validation
- EF Core interceptor
- Logging and diagnostics
GitHub
https://github.com/birupakhya2000/DBGuard
Final Thoughts
This is a common problem many developers face.
I’d love feedback and suggestions from the community 🙌
Top comments (0)