开发者

.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 have manually set the field BlogContent to be of ntext type (16 bytes) in the SQL CE4 database.

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

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

I have tried setting the annotation for [Column(TypeName="nt开发者_运维问答ext")], but this makes no difference. When I loop trough the EntityValidationErrors collection, the problem is caused by BlogContent and the error says:

String cannot be longer than 4000 characters

How can I define my model to have an ntext field for BlogContent?

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


I have solved it, you need to use:

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

See details here: 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".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜