.NET MVC: how to define ntext field in Code-First for SQL CE?

I have the following model:

public class Blog { public int BlogID { get; set; } public int CategoryID { get; set; } [MaxLength(70)] [Required] public string BlogTitle { get; set; } [Column(TypeName="ntext")] public string BlogContent { get; set; } } 

I manually set the BlogContent field to ntext (16 bytes) in the SQL CE4 .

However, every time I try to insert text longer than 4000 characters, it gives the following error:

Validation failed for one or more legal entities. See the "EntityValidationErrors" property for more details.

I tried to set the annotation for [Column(TypeName="ntext")] , but that doesn't make any difference. When I loop through the EntityValidationErrors collection, the problem is caused by BlogContent and the error says:

The string cannot be longer than 4000 characters.

How can I determine if my model has an ntext field for BlogContent ?

It seems that any data annotations are ignored; it is assumed that a string without MaxLength by default limited to 4000 characters.

+7
source share
1 answer

I solved this, you need to use:

 [Column(TypeName="ntext")] [MaxLength] public string BlogContent { get; set; } 

See here for more details: http://www.cloudonedesign.com/Blog/Post/how-to-define-ntext-fields-using-code-first-in-net-30

To create an ntext column in the database and let the model check actually know that the string can be longer than 4000 characters, we must use these two elements:

[Column(TypeName="ntext")] : This will tell Code-First to create an ntext in the database.

[MaxLength] : using the default constructor, it will occupy the maximum length of the database field, instead of guessing the maximum length of the row, which is 4000. If this is absent or you explicitly set the maximum length, for example [MaxLength(8000)] , model checking will raise errors by saying: "The maximum line length is 4000 characters."

+21
source

All Articles