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; } }
我已在sql CE4数据库中手动将字段BlogContent设置为ntext类型(16字节).
但是,每次我尝试插入超过4000个字符的文本时,都会出现以下错误:
Validation Failed for one or more
entities. See ‘EntityValidationErrors’
property for more details
我已经尝试为[Column(TypeName =“ntext”)]设置注释,但这没有区别.当我通过EntityValidationErrors集合循环时,问题是由BlogContent引起的,错误说:
String cannot be longer than 4000 characters
如何定义我的模型以获得BlogContent的ntext字段?
似乎忽略了任何数据注释;假设没有MaxLength的字符串默认限制为4000个字符.
解决方法
[Column(TypeName="ntext")] [MaxLength] public string BlogContent { get; set; }
详情请见:
http://www.cloudonedesign.com/Blog/Post/how-to-define-ntext-fields-using-code-first-in-net-30
In order to create an
ntext
column in the database,and allow model validation
to actually know that the string length can be more than 4,000 characters,we
have to use these two items:
[Column(TypeName="ntext")]
: This will tell Code-First to generate an
ntext field in the database.
[MaxLength]
: By using the default
constructor,it will take the maximum length of the database field,
instead of guessing the maximum length for a string,which is 4,000. If this is
missing or you explicitly set the maximum length such as[MaxLength(8000)]
,model validation will raise errors saying “String maximum length is 4,000 characters”.