-3

I have a SQL Server table Workers and it has a column Name which is of datatype nvarchar(20).

I am using an ADO.NET Entity Data Model.

In my project, I want to limit user input to 20 characters (limit of my Name column).

How can I get this data through C# code and use it?

EDIT The solution I need is a C# code that gives me the 20(limit of my Name column) so I can dynamically use it as a validation data. By that, If I change this limit on my database it will automatically use the updated data so I won't go to my input and manually change it for new limit.

My table will be a c# class by EntityFramework so I will have a class named Workers and Name as a property of it. I am looking for the limit of this property.

SoruDev
  • 1
  • 2
  • 1
    You can start with https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.maxlengthattribute. But you give no information about your frontend. – Mario Jun 15 '22 at 12:26
  • This is a application , not an SQL issue; this would be part of input validation and you can either check the length of the string input or truncate the string. Also, `name` is not a good SQL field name – Peter Smith Jun 15 '22 at 12:34
  • @PeterSmith For retrieving the info he needs SQL can be used, so I am not sure if it is only an application question. I agree on the name issue, though this is subject to opinions off course – GuidoG Jun 15 '22 at 12:37
  • @GuidoG A better solution is to use `nvarchar(MAX)` and also have proper client-side validation as a matter of course – Peter Smith Jun 15 '22 at 12:45
  • 2
    @PeterSmith I strongly dissagree there, when there is only 20 characters allowed then the database must have nvarchar(20), when the client side can also restrict this that is a nice to have, but the database rules in every case. – GuidoG Jun 15 '22 at 13:11

2 Answers2

1

All this information is stored in the SQL Server system catalog views in the sys schema.

You can e.g. get the max length of a particular column like this:

SELECT
    c.Name, c.max_length
FROM
    sys.columns c
INNER JOIN
    sys.tables t ON t.object_id = c.object_id
WHERE
    t.Name = 'Workers'
    AND c.Name = 'Name'
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
-1

Value is a reserved SQL word,so add [] to it.