Can't limit length of input with ado.net

Trying to limit maximum length of input but can't. So if input length is 10, code does not limits to three. What is my mistake?

Here is code:

using Microsoft.Data.SqlClient;

async void FillTable()
{
    string connectionString = "Server=(localdb)\\mssqllocaldb;Database=adonetdb;Trusted_Connection=True;";

   Console.WriteLine("Enter name:");
   string name = Console.ReadLine();

   Console.WriteLine("Enter age:");
   int age = int.Parse(Console.ReadLine());

   string sqlExpression = $"USE adonetdb; INSERT INTO Users (Name, Age) VALUES ('{name}', {age})";
   using SqlConnection connection = new(connectionString);
   await connection.OpenAsync();
   SqlCommand command = new(sqlExpression, connection);
   command.Parameters.Add("@name", System.Data.SqlDbType.NVarChar, 3).Value = name;
   command.Parameters.AddWithValue("@age", age);
   int number = await command.ExecuteNonQueryAsync();
   Console.WriteLine("Finish");
}

FillTable();

Console.Read();

Please help.


The problem here is that you haven't used the parameter at all. Try instead:

const string sqlExpression = "USE adonetdb; INSERT INTO Users (Name, Age) VALUES (@name, @age)";

This will also solve SQL injection and i18n/l10n problems.

As a side note: spending your time messing with the ADO.NET API isn't a great use of your time; tools like Dapper will do all of this for you, correctly:

using SqlConnection connection = new(connectionString);
await connection.ExecuteAsync(sqlExpression, new { name, age }); // job done