在EF6中将字符串列设置为可为空

Ehs*_*bar 13 c# asp.net-mvc entity-framework asp.net-mvc-4

我有一个模型,我创建它EF 150:

public partial class Comment
{
    [DisplayName("????? ???")]
    public int Id { get; set; }

    [Required(ErrorMessage = "??? ??? ?? ???? ????")]
    [DisplayName("??? ???")]
    public string CommentText { get; set; }

    [DisplayName("????? ??????? ")]
    public long LikeCount { get; set; }

    [DisplayName("????? ????????")]
    public long DisLikeCount { get; set; }

    [DisplayName("????? ?????? ")]
    public System.DateTime PublishDate { get; set; }

    [DisplayName("????? ????? ")]
    public string Visible { get; set; }

    [DisplayName("??? ?????? ")]
    public Nullable<string> AutherUserName { get; set; }

    [DisplayName("????? ???????")]
    public Nullable<int> CommentFKId { get; set; }

    [DisplayName("????? ?????")]
    public Nullable<int> StudentId { get; set; }

    [DisplayName("????? ????? ")]
    public Nullable<int> ContentId { get; set; }

    public virtual Comment Comments { get; set; }
    public virtual Comment Comment1 { get; set; }
    public virtual Student Student { get; set; }
    public virtual Content Content { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我的模型中有几个Nullable int列,但我无法将字符串列设置为null:

public Nullable<string> AutherUserName { get; set; }
Run Code Online (Sandbox Code Playgroud)

我收到了这个错误:

类型'string'必须是非可空值类型才能在泛型类型或方法'System.Nullable'中将其用作参数'T'

我正在使用MVC4

Mar*_*llo 29

字符串是引用类型,因此已经"可以为空".只有值类型(例如int)可以为空,因为否则它们不能为空.

  • 如果模型上的字符串属性的值为null,则它将为null yes.如果它是"空白"(空字符串),则它不会为空.要使字符串列不可为空,您也可以使用[Required]属性. (5认同)