I am working on a project and I would like to set some properties to optional in code first approach. In my class file I have added [Required]
to properties I would set to not null in SQL and properties that do not have [Required]
should set to allow null in SQL, but for some properties that contains ID in it, it sets to not null in SQL. Below is my sample class that contains properties that should be used when generating tables in the database. I would like to set EnvironmentLastDeployedId
property to optional when it creates new database in 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; }
}
In my Context class file, I tried to use Fluent API, but I only get IsRequired
method, but not IsOptional
or something that allows me to set table column to allow null in database.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Version>()
.Property(p => p.EnvironmentLastDeployedId).IsRequired();
}
If you want to allow null values for int you just need to use int?:
public int? ApplicationId { get; set; }
This will map to a nullable column in SQL, so it won't throw any exception when trying to store a record with a null value for that column.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With