To my knowledge, the RequiredAttribute data annotation for string types only results in the corresponding database table column being created as NOT NULL.
I believe this is not sufficient. Moreover, it is in conflict with user interface layers, like MVC, which cannot reliably discern between an input being null or an empty string.
So I'd like to suggest to amend the behaviour of the RequiredAttribute so that it will additionally create the following T-SQL CHECK constraint: CHECK (LEN(LTRIM(RTRIM( {columnName} ))) > 0).
So an entity definition like the following:
Similar for the MinLengthAttribute data annotation. It should, too, add the following CHECK constraint: CHECK(LEN( {columnName} ) > x ).
So an entity definition like the following:
Applying both attributes in conjunction should merge the generated CHECK constraint into one:
I'm not sure whether the LTRIM/RTRIM should by mandatory in above cases or optionally added by providing an additional constructor parameter to above data annotations.
... your thoughts?
I believe this is not sufficient. Moreover, it is in conflict with user interface layers, like MVC, which cannot reliably discern between an input being null or an empty string.
So I'd like to suggest to amend the behaviour of the RequiredAttribute so that it will additionally create the following T-SQL CHECK constraint: CHECK (LEN(LTRIM(RTRIM( {columnName} ))) > 0).
So an entity definition like the following:
public class MyEntity
{
public int Id;
[Required]
[Index(“UK_MyEntity_Name”, IsUnique= true)]
public string Name;
}
should result in the following DDL:CREATE TABLE MyEntities
( Id INT CONSTRAINT PK_MyEntities PRIMARY KEY IDENTITY
, Name NVARCHAR(MAX) NOT NULL CONSTRAINT UK_MyEntity_Name UNIQUE CONSTRAINT CK_MyEntity_Name CHECK (LEN(LTRIM(RTRIM(Name))) > 0)
)
.Similar for the MinLengthAttribute data annotation. It should, too, add the following CHECK constraint: CHECK(LEN( {columnName} ) > x ).
So an entity definition like the following:
public class MyEntity
{
public int Id;
[MinLength(15)]
[Index(“UK_MyEntity_Name”, IsUnique= true)]
public string Name;
}
should result in the following DDL:CREATE TABLE MyEntities
( Id INT CONSTRAINT PK_MyEntities PRIMARY KEY IDENTITY
, Name NVARCHAR(MAX) CONSTRAINT UK_MyEntity_Name UNIQUE CONSTRAINT CK_MyEntity_Name CHECK (LEN(Name) > 15)
)
.Applying both attributes in conjunction should merge the generated CHECK constraint into one:
public class MyEntity
{
public int Id;
[Required]
[MinLength(15)]
[Index(“UK_MyEntity_Name”, IsUnique= true)]
public string Name;
}
should result in the following DDL:CREATE TABLE MyEntities
( Id INT CONSTRAINT PK_MyEntities PRIMARY KEY IDENTITY
, Name NVARCHAR(MAX) NOT NULL CONSTRAINT UK_MyEntity_Name UNIQUE CONSTRAINT CK_MyEntity_Name CHECK (LEN(LTRIM(RTRIM(Name))) > 15)
)
.I'm not sure whether the LTRIM/RTRIM should by mandatory in above cases or optionally added by providing an additional constructor parameter to above data annotations.
... your thoughts?