Property / Field Types - string v nvachar

Dean Everhart 1,541 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

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | ASP.NET | Other
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.