Property / Field Types - string v nvachar

Dean Everhart 1,496 Reputation points
2023-02-27T15:05:38.3333333+00:00

Premise

Is the correct way to create properties (fields) to hold text in .net, to designate as "string" property types in the model which, when migrated and database created, are created by default as nvachar(max)?

When I am creating a property to hold text in a model that I know I want to be a nvachar(50) or nvachar(25), is there a way to designate that in the model... Is string the only way to create a text field in a model in .net?

or...

...do you create the property as a string in .net and change the default nvachar(max) to nvachar(50) or nvachar(25) in MSSMS?

i.e.

Is there a way to create a string property in .net that is nvachar(25), rather than, what seems to be, the default of nvachar(max)?

.net Model (string property designated in model for field to hold text)

using System.ComponentModel.DataAnnotations;            // Date Format

namespace Wellbeing.Models
{
    public class Quotes
    {
        public int Id { get; set; }

        public string? Text { get; set; }

    }
}

Migration (what was created as "string" becomes nvachar(max) by default when migrated)

        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "TableName",
                columns: table => new
                {
                    Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),

                    Text = table.Column<string>(type: "nvarchar(max)", 
nullable: true)

MSSMS

User's image

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,167 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,256 questions
{count} votes