How to set optional field in code first approach in ASP.NET 5 and EF7 entity-framework entity-framework-6


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; }

    public string PackageName { get; set; }
    public string VersionName { get; set; }
    public string OriginalPackageName { get; set; }

    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)
            .Property(p => p.EnvironmentLastDeployedId).IsRequired();
2/5/2016 4:14:03 PM

Accepted Answer

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.

2/5/2016 4:33:52 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow