【问题标题】:ASP.Net MVC3 SQL NullableASP.Net MVC3 SQL 可以为空
【发布时间】:2012-07-03 03:39:48
【问题描述】:

我目前正在开发一个 ASP.Net MVC3 项目。我已经设置好了,所以我的 sql 数据库根据我创建的类创建了它的表,我需要知道是否有办法设置它,以便变量可以为空,例如:

   public class Cart
   {
       [Key]
       public int RecordId { get; set; }
       public string CartId { get; set; }
       public int VideoId { get; set; }
       public int CandyId { get; set; }
       public int Count { get; set; }
       public System.DateTime DateCreated { get; set; }
       public virtual Video Video { get; set; }
       public virtual Candy Candy { get; set; }
    }

有没有办法将 VideoId 和 Candy Id 设置为空?他们现在出现的方式是作为其他表的外键。非常感谢任何和所有帮助。

【问题讨论】:

  • 应该VideoId Video表的外键吗?

标签: sql asp.net-mvc-3 null ef-code-first data-annotations


【解决方案1】:

你有两个选择:

1) 使用 int 声明您的属性?

 public int? VideoId { get; set; }
 public int? CandyId { get; set; }

2) 使用常规 int 声明您的属性,但处理当您获得空值时应该发生的情况。

 VideoId = thisMightBeNull ?? 0; //?? means, if the variable is null then use 0

使用第一个选项的缺点是,如果您想将 VideoId 或 CandyId 分配给一个新变量,它应该是 int?,有时它会变得混乱。 使用第二个选项,您不会遇到这个问题,但这意味着您应该处理在那一刻分配的内容(默认值)。

【讨论】:

    【解决方案2】:

    您可以使用? 符号使VideoIdCandyId 可以为空:

    public int? VideoId { get; set; }
    public int? CandyId { get; set; }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多