DEV Community

RzR
RzR

Posted on

Avoid "String or binary data would be truncated" or how to save safe strings.

In the current reality almost everyone and everyday interact with data and executing base CRUD operations. The most common exception met is:

String or binary data would be truncated” or in other words…

The maximum allowed field/property length was exceeded and the operation can’t be finished”.

This error happens when the length of string data exceeds the maximum length defined for a column—resulting in disruptive runtime failures and tedious debugging. Manually trimming strings or validating their lengths can be cumbersome, especially in projects with numerous entities or frequent changes.

That is where EntityMaxLengthTrim comes in.

EntityMaxLengthTrim is a lightweight .NET library designed to automate the truncation of string values based on their maximum length constraints. It inspects entity properties adorned with standard data-annotation attributes—such as MaxLength, StringLength or MaxAllowedLength —and a custom attribute for extra flexibility. The library trims overly long inputs before they reach the database, helping you avoid runtime exceptions while preserving code cleanliness and maintainability.

Why This Matters

The value of a library like EntityMaxLengthTrim lies in safety and consistency. By applying length rules at the entity level, you ensure that all string values conform to your schema before they reach the database. This reduces runtime surprises, prevents data loss, and keeps your codebase focused on business rules instead of plumbing.

How EntityMaxLengthTrim Works

At its core, EntityMaxLengthTrim relies on interception and reflection to ensure your entity strings always conform to the maximum allowed length before ORM attempts to persist them. Let us unpack the mechanics.

Examples:

Example 1:

  • So from the beginning first action is to define the data model.
public class FooModel
{
    public Guid Id { get; set; }

    public string Name { get; set; }

    public string FullName { get; set; }

    public string Description { get; set; }
}
Enter fullscreen mode Exit fullscreen mode
  • The next step is to decorate every string property which you would like to apply the maximum length rule with one of the following attribute: MaxLength, StringLength or MaxAllowedLength.
public class FooModel
{
    public Guid Id { get; set; }

    [MaxLength(25)]
    public string Name { get; set; }

    [StringLength(120)]
    public string FullName { get; set; }

    [MaxAllowedLength(512)]
    public string Description { get; set; }
}
Enter fullscreen mode Exit fullscreen mode
  • One of the last step is to call the methods which will make the magic.
var parsedData = sourceEntityData.ToSafeStoreStrings();
Enter fullscreen mode Exit fullscreen mode

Example 2:

  • For this example, the first step is the same as in Example 1, we need to define the data model.
public class FooModel
{
    public Guid Id { get; set; }

    public string Name { get; set; }

    public string FullName { get; set; }

    public string Description { get; set; }
}
Enter fullscreen mode Exit fullscreen mode
  • The next step we nedd to execute is to inheritance a base class EntityPropChangeEventBase which implement the interface INotifyPropertyChanged and event PropertyChangedEventHandler. In the data model class we need to convert default property to property with backing field

As result we will see:

public class FooModel : EntityPropChangeEventBase
{
    private string _name;
    private string _fullName;
    private string _description;

    public Guid Id Type { get; set; }

    [MaxLength(25)]
    public string Name
    {
        get => _name;
        set => _name = value;
    }

    [StringLength(120)]
    public string FullName
    {
        get => _fullName;
        set => _fullName = value;
    }

    [MaxAllowedLength(512)]
    public string Description
    {
        get => _description;
        set => _description = value;
    }
}
Enter fullscreen mode Exit fullscreen mode
  • And the last step is to implement functionalities from base class
public class FooModel : EntityPropChangeEventBase
{
    private string _name;
    private string _fullName;
    private string _description;

    public Guid Id { get; set; }

    [MaxLength(25)]
    public string Name
    {
        get => _name;
        set
        {
            if (_name == value) return;
            _name = value;
            OnPropertyChanged(this, nameof(Name));
        }
    }

    [StringLength(120)]
    public string FullName
    {
        get => _fullName;
        set
        {
            if (_fullName == value) return;
            _fullName = value;
            OnPropertyChanged(this, nameof(FullName));
        }
    }

    [MaxAllowedLength(512)]
    public string Description
    {
        get => _description;
        set
        {
            if (_description == value) return;
            _description = value;
            OnPropertyChanged(this, nameof(Description));
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

So this is the result, but when we take a look in the result class first think is that: is too much code for the set property.
For this case exist another method SetContent which will simplify the code:

public class FooModel : EntityPropChangeEventBase
{
    private string _name;
    private string _fullName;
    private string _description;

    public Guid Id { get; set; }

    [MaxLength(25)]
    public string Name
    {
        get => _name;
        set => SetContent(this, nameof(Name), ref _name, ref value);
    }

    [StringLength(120)]
    public string FullName
    {
        get => _fullName;
        set => SetContent(this, nameof(FullName), ref _fullName, ref value);
    }

    public string Description
    {
        get => _description;
        set => SetContent(this, nameof(Description), ref _description, ref value, 512);
    }
}
Enter fullscreen mode Exit fullscreen mode

If we take a look at the last code example, we can see that in the two cases was used the rule for maximum text length was used as an attribute, but in one case, the length was passed as an input parameter for SetContent method.

As a simple conclusion, the SetContent can be used in dependency on the code environment. The next time this data model is supplied with data, the maximum length rule will be triggered.

These two examples are not all the use cases of when and how it can be used. For all publicly available methods, you can check the repository in GitHub; it all depends on the application's business logic and core environment, and requirements.

The repository link:

GitHub logo I-RzR-I / EntityMaxLengthTrim

One important thing about this repository, you have the possibility to avoid database exceptions related to exceeding the limit of the maximum allowed length of the string type columns. To specify the maximum allowed string length you can use data annotation attributes predefined in `System.ComponentModel.DataAnnotations` or a new custom attribute.

Note This repository is developed for .netstandard1.5+ and net framework 4.5

NuGet Version Nuget Downloads

One important thing about this repository is that you can truncate input string in the fields/properties at the maximum allowed length from DB. To specify the maximum allowed string length you can use data annotation attributes predefined in System.ComponentModel.DataAnnotations or a new custom attribute.

The maximum allowed length will be searched in the attributes(you may use one of these):

  • MaxLengthAttribute -> ([MaxLength(x)]);
  • StringLengthAttribute -> ([StringLength(x)]);
  • MaxAllowedLengthAttribute -> ([MaxAllowedLength(x)]).

To get acquainted with a more detailed description, please check the content table at the first point.

Once you use this repository, you have the possibility to avoid database exceptions related to exceeding the limit of the maximum allowed length and the string type columns.

No additional components or packs are required for use. So, it only needs to be added/installed in the project…

Top comments (0)