2011-06-16 51 views
7

我有以下模式:.NET MVC:如何在用於SQL CE的Code-First中定義ntext字段?

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; } 
} 

我已經手動設置字段BlogContent是在SQL CE4數據庫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

我如何定義我的模型有一個ntext領域BlogContent

似乎任何數據註釋都被忽略;假定沒有MaxLength的字符串默認限制爲4000個字符。

回答

21

我已經解決了它,你需要使用:

[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".

相關問題