EF 4.1 Code First:"DateTime'类型的非空值"问题

Pau*_*own 13 asp.net-mvc entity-framework code-first ef-code-first asp.net-mvc-3

在初始开发和测试之后,我现在将我的MVC3应用程序指向包含实时数据的现有数据库.

但是,我收到与名为Date1的字段"datetime"相关的错误.

The 'Date1' property on 'StaffAttachment' could not be set to a 'null' value. You must set this property to a non-null value of type 'DateTime'. 
Run Code Online (Sandbox Code Playgroud)

这告诉我日期中的所有行都必须有一个日期而不是空吗?如果我不想在特定行上设置日期,该怎么办?

有人可以就解决这个问题提出建议吗?

谢谢保罗

编辑1(发布模型)

public class StaffAttachment
{
    [Key]
    public int AttachmentID { get; set; }

    public int? StaffID { get; set; }

    public int? TypeID { get; set; }

    [Required]
    [DisplayName("Proof of ID")]
    public int? AttachmentTypeID { get; set; }

    [Required]
    [DisplayName("ID Reference")]
    public string Reference1 { get; set; }

    public string Reference2 { get; set; }

    public string DateType { get; set; }

    [DisplayName("Expiry Date")]
    public DateTime Date1 { get; set; }

    [Required]
    public DateTime Date2 { get; set; }

    public DateTime Date3 { get; set; }

    public DateTime Date4 { get; set; }

    public string AttachmentPath { get; set; }

    public int? ValidatedUserID { get; set; }

    public DateTime ValidatedDate { get; set; }

    public int? CreatedUserID { get; set; }

    public DateTime CreatedDate { get; set; }

    public int? EditedUserID { get; set; }

    public DateTime EditedDate { get; set; }

    public TimeSpan TimeStamp { get; set; }

    public string FileName { get; set; }

    public byte[] FileImage { get; set; }

    public int AttachmentSection { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Bro*_*ass 25

这告诉我日期中的所有行都必须有一个日期而不是空吗?如果我不想在特定行上设置日期,该怎么办?

看起来您指向的DB具有空值Date1.如果您确实不想为所有行设置日期,只需将您的Date1属性设为可为空:

public DateTime? Date1{get;set;}
Run Code Online (Sandbox Code Playgroud)

或者,您可以为没有当前通过SQL设置的日期时间的所有行输入默认日期.


Lew*_*wis 8

public DateTime? Date1 { get; set; }
Run Code Online (Sandbox Code Playgroud)

使用这个,你的模型需要被告知数据库中可以有空值,否则它会假设没有.