【问题标题】:Set a string column to nullable in EF6在 EF6 中将字符串列设置为可为空
【发布时间】:2014-05-18 03:51:13
【问题描述】:

我有一个模型是我在 EF6 上创建的:

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

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

public Nullable<string> AutherUserName { get; set; }

我得到了这个错误:

类型“string”必须是不可为空的值类型,才能在泛型类型或方法“System.Nullable”中用作参数“T”

我正在使用 MVC4

【问题讨论】:

标签: c# asp.net-mvc entity-framework asp.net-mvc-4


【解决方案1】:

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

【讨论】:

  • 所以你的意思是如果我的列的文本框是空的,它会是空的?
  • 如果模型上的string属性的值为null,则为null yes。如果它是“空白”(空字符串),那么它就不会为空。对于不可为空的字符串列,您也可以使用 [Required] 属性。
  • 如果我的数据库优先 not-null 设计产生了一个具有普通 string 属性的类,有什么建议吗?它没有包含 [Required] 属性,但在它的 ModelBuilding 中,它推测该列是not-null;有没有一种流畅的方法来确保该属性是null?如果不是,则更改它?
猜你喜欢
  • 1970-01-01
  • 2015-12-16
  • 2017-11-05
  • 2013-12-28
  • 2016-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多