0

I use Nhibernate and sometimes I get error like "String or binary data would be truncated in table..." because of sql restrictions. Is there a way to limit string length? I limit properties individualy like here.


public void myMethod()
{
    myClass myClass1= new MyClass()
    {
       id = 1,
       prop1 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat"
    }
    saveMethod(myClass1);
}

public void saveMethod(myClass entity)
{
    entity.prop1=entity.prop1?.Substring(0,Math.Min(100,entity.prop1.Length));
    _repository.insert(entity);
}
public class myClass
{
    public virtual int id { get; set; }
    public virtual string prop1 { get; set; }
}

I use MSSQL for database.

1

1 Answer 1

1
public virtual string Prop1 { get => _prop1; set { _prop1 = value?.Substring(0, MaxLength); OnPropertyChanged(); } }

or with https://nhibernate.info/doc/validator/nhibernate-validator-1-0-0-documentation

[Length(Max=MaxLength)]
public virtual string prop1 { get; set; }

Not the answer you're looking for? Browse other questions tagged or ask your own question.