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)
如果你想允许 int 为空值,你只需要使用 int?:
public int? ApplicationId { get; set; }
Run Code Online (Sandbox Code Playgroud)
这将映射到 SQL 中的可空列,因此在尝试存储该列的空值记录时不会引发任何异常。