[entity-framework] Nullable property to entity field, Entity Framework through Code First

Using the data annotation Required like so:

[Required]
public int somefield {get; set;}

Will set somefield to Not Null in database, How can I set somefield to allow NULLs?, I tried setting it through SQL Server Management Studio but Entity Framework set it back to Not Null.

This question is related to entity-framework asp.net-mvc-3 code-first nullable

The answer is


Just omit the [Required] attribute from the string somefield property. This will make it create a NULLable column in the db.

To make int types allow NULLs in the database, they must be declared as nullable ints in the model:

// an int can never be null, so it will be created as NOT NULL in db
public int someintfield { get; set; }

// to have a nullable int, you need to declare it as an int?
// or as a System.Nullable<int>
public int? somenullableintfield { get; set; }
public System.Nullable<int> someothernullableintfield { get; set; }

In Ef .net core there are two options that you can do; first with data annotations:

public class Blog
{
    public int BlogId { get; set; }
    [Required]
    public string Url { get; set; }
}

Or with fluent api:

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .Property(b => b.Url)
            .IsRequired(false)//optinal case
            .IsRequired()//required case
            ;
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

There are more details here


The other option is to tell EF to allow the column to be null:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<SomeObject>().Property(m => m.somefield).IsOptional();            
        base.OnModelCreating(modelBuilder);
}

This code should be in the object that inherits from DbContext.


Jon's answer didn't work for me as I got a compiler error CS0453 C# The type must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method

This worked for me though:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<SomeObject>().HasOptional(m => m.somefield);
    base.OnModelCreating(modelBuilder);
}

Examples related to entity-framework

Entity Framework Core: A second operation started on this context before a previous operation completed EF Core add-migration Build Failed Entity Framework Core add unique constraint code-first 'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Working with SQL views in Entity Framework Core How can I make my string property nullable? Lazy Loading vs Eager Loading How to add/update child entities when updating a parent entity in EF

Examples related to asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC

Examples related to code-first

ALTER TABLE DROP COLUMN failed because one or more objects access this column CREATE DATABASE permission denied in database 'master' (EF code-first) Nullable property to entity field, Entity Framework through Code First Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships? Entity Framework Code First - two Foreign Keys from same table Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework The model backing the <Database> context has changed since the database was created

Examples related to nullable

Laravel Migration Change to Make a Column Nullable How to set null to a GUID property How to set null value to int in c#? Can't find @Nullable inside javax.annotation.* Check if Nullable Guid is empty in c# How to declare a type as nullable in TypeScript? Java check if boolean is null How to use @Nullable and @Nonnull annotations more effectively? Nullable property to entity field, Entity Framework through Code First The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'