101

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.

shA.t
  • 16,580
  • 5
  • 54
  • 111
chrisramon
  • 1,253
  • 2
  • 8
  • 8
  • 8
    I was actually searching to find out how to get CodeFirst to do NOT NULL and your question answered it perfectly! Thanks :) – Andy Clarke Oct 31 '12 at 10:34

4 Answers4

145

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; }
danludwig
  • 46,965
  • 25
  • 159
  • 237
  • 7
    In your question your property is a string. To make an int allow nulls, you have to declare it as a nullable int, like so: `public int? somenullableintfield { get; set; }` – danludwig May 22 '12 at 22:20
  • Yes, my mistake, i need allow null to int types. – chrisramon May 22 '12 at 22:21
  • 3
    what about the situation (edge case, but one I am facing), the attributes are used for business rule validation and ease of use with mvc, but need to allow user to save partially completed forms (i.e. long forms that may take a while to do). I need to be able to allow EF to create columns that allow nulls.. guessing its the modebuilder used in oncreating, but don't know how – Jon Aug 01 '12 at 14:50
  • what happen if you put [Required] on a nullable property like "public int? somenullableintfield { get; set; }"? – AXMIM Aug 03 '16 at 17:17
  • @AXMIM...a little late...but [Required] data annotation overrides int?. – Chris Catignani Jan 11 '20 at 19:48
  • @danludwig I made a class where there is no required but in the DB it is showing not null. – username_allowed Feb 12 '22 at 09:19
  • I believe as of C# 10, you will explicit have to add ? to string also, in order to have mssql server table display checkmark under 'allow nulls'. Hence a string property would have to look like: public string? name {get; set;} – Mohammad S. Jun 02 '22 at 11:08
37

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.

shA.t
  • 16,580
  • 5
  • 54
  • 111
Jon
  • 15,110
  • 28
  • 92
  • 132
  • 1
    Perfect, thanks. This solved my problem with [Required] strings, allowing them to be null in the db, but enforcing a requirement in MVC helpers – Derrick Dec 28 '12 at 17:52
  • 2
    Why don't you use ViewModels? Than it could be required in the viewmodel and not required in the real model. – Roel Nov 30 '15 at 10:18
  • it might be part of the model and viewmodel, but an optional field based on some business logic. danludwig's answer is the more complete solution (http://stackoverflow.com/a/10710934/6486) – Jon Nov 30 '15 at 11:02
20

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

public class Blog
{
    public int BlogId { get; set; } // optinal case

    [Required]
    public string Url { get; set; } // required case
}

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

nzrytmn
  • 6,193
  • 1
  • 41
  • 38
4

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);
}
Jon
  • 9,156
  • 9
  • 56
  • 73