我正在一个项目上,我想在代码优先方法中将一些属性设置为可选。在我的类文件中,我添加[Required]
了一些属性,在SQL中我将其设置为不为null,而在SQL中不具有该属性的属性[Required]
应设置为允许null,但对于其中包含ID的某些属性,在SQL中该属性设置为非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; }
}
在我的Context类文件中,我尝试使用Fluent API,但我只获取IsRequired
方法,但没有获取方法,IsOptional
或者使我可以设置表列以允许数据库中为null的东西。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Version>()
.Property(p => p.EnvironmentLastDeployedId).IsRequired();
}
如果要为int允许使用空值,则只需使用int ?:
public int? ApplicationId { get; set; }
这将映射到SQL中的可为空的列,因此在尝试存储该列具有空值的记录时不会引发任何异常。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句