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

Ray*_*Ray 3 asp.net entity-framework entity-framework-6 asp.net-core-mvc

我正在处理一个项目,我想在代码优先方法中将一些属性设置为可选。在我的类文件中,我已添加[Required]到属性中,我将在 SQL 中设置为 not null,而没有的属性[Required]应设置为在 SQL 中允许为 null,但对于其中包含 ID 的某些属性,它在 SQL 中设置为 not null。下面是我的示例类,其中包含在数据库中生成表时应使用的属性。我想EnvironmentLastDeployedId在 MSSQL 中创建新数据库时将属性设置为可选。

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; }
}
Run Code Online (Sandbox Code Playgroud)

在我的 Context 类文件中,我尝试使用 Fluent API,但我只获取IsRequired方法,但不能IsOptional或允许我将表列设置为允许数据库中的空值的东西。

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

joa*_*ins 6

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

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

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

  • 对于`string` 类型,你不能写`public string?myString { 获取;放; }` 因为字符串类型已经是`nullable`了。如果您希望它们不是可选的,只需在它们之前添加 `[Required]`。 (4认同)
  • @masoud-keshavarz 这个文档谈到了“字符串?” - 如果启用可为空引用类型,则将根据其 .NET 类型的 C# 可为空性来配置属性:字符串?将配置为可选,而字符串将根据需要配置。https://learn.microsoft.com/en-us/ef/core/modeling/required-optional?tabs=without-nrt%2Cdata-annotations (2认同)