DEV Community

Birupakhya Dash
Birupakhya Dash

Posted on

Fixing the "String or Binary Data Would Be Truncated" Error in EF Core

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Now insert:

"ThisIsAVeryLongNameThatExceedsLimit"
Enter fullscreen mode Exit fullscreen mode

SQL Server throws:

String or binary data would be truncated
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

DBGuard returns:

DBGuard Validation Failed

Table: Users
Column: FirstName
Allowed Length: 20
Actual Length: 45

Suggestion: Trim input or increase column length
Enter fullscreen mode Exit fullscreen mode

Installation

dotnet add package DBGuard
Enter fullscreen mode Exit fullscreen mode

Usage

builder.Services.AddDbGuard(connectionString);

builder.Services.AddDbContext<AppDbContext>((sp, options) =>
{
    var interceptor = sp.GetRequiredService<DbGuardInterceptor>();

    options.UseSqlServer(connectionString)
           .AddInterceptors(interceptor);
});
Enter fullscreen mode Exit fullscreen mode

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)