model class attribute string length as nvarchar max

How can I assign ms sql server data type nvarchar max length in model class attribute. Suppose I have one attribute, StudentName

public string StudentName { get; set; }

How can I make StudentName datatype as nvarchar max?

2 answers

  • answered 2020-11-25 07:52 Mehran Gharzi

    If you do not want to limit the value of your string MaxLength (200) why use MaxLength? You just need to remove the MaxLength(200) to change your model to nvarchar max.

    If you want to use a limit of 200 characters only on your controller and views, it is better to use ViewModel.

  • answered 2020-11-25 08:13 Hassan Monjezi

    There is a Column() attribute, which you can use to specify exact SQL Server data type. for example:

    public string StudentName { get; set; }

    Note: MaxLength attribute will be overridden by the Column attribute, but in model binding StudentName would validated by its MaxLength attribute.

    And if you prefer, you can achieve this using Fluent API in this way:

     builder.Property(x => x.StudentName)

    By the way, it is not practical to filter user input with MaxLength, but in database set the field type nvarchar(max).