如何在 ASP.NET 5 和 EF7 中的代码优先方法中设置可选字段

How to set optional field in code first approach in ASP.NET 5 and EF7

我正在做一个项目,我想在代码优先方法中将一些属性设置为可选。在我的 class 文件中,我已将 [Required] 添加到我将在 SQL 中设置为非空的属性,而没有 [Required] 的属性应设置为允许在 [=26] 中为空=],但对于其中包含ID的一些属性,它在SQL中设置为not null。下面是我的示例 class,其中包含在数据库中生成 table 时应使用的属性。当它在 MSSQL.

中创建新数据库时,我想将 EnvironmentLastDeployedId 属性 设置为可选
public class Version
{
    public int Id { get; set; }

    [Required]
    public string PackageName { get; set; }
    public string VersionName { get; set; }
    public string OriginalPackageName { get; set; }

    [Required]
    public string CommitID { get; set; }
    public string CommitMessage { get; set; }
    public int ApplicationId { get; set; }
    public Application Application { get; set; }
    public string CreatedBy { get; set; }
    public int EnvironmentLastDeployedId { get; set; }
    public Environment EnvironmentLastDeployed { get; set; }
    public int StatusId { get; set; }
    public Status Status { get; set; }
    public DateTime CreatedOn { get; set; }
    public DateTime ModifiedOn { get; set; }
}

在我的上下文 class 文件中,我尝试使用 Fluent API,但我只得到 IsRequired 方法,但没有 IsOptional 或其他允许我使用的方法设置 table 列以在数据库中允许空值。

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Version>()
            .Property(p => p.EnvironmentLastDeployedId).IsRequired();
    }

如果你想允许 int 的空值,你只需要使用 int?:

public int? ApplicationId { get; set; }

这将映射到 SQL 中的可为空的列,因此在尝试为该列存储具有空值的记录时不会抛出任何异常。