Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
    }
like image 806
Ray Avatar asked Feb 08 '23 19:02

Ray


1 Answers

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.

like image 75
joaoruimartins Avatar answered May 15 '23 04:05

joaoruimartins