Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 914
chrisramon Avatar asked May 22 '12 21:05

chrisramon


People also ask

How do you make a column nullable in code first approach?

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

Can a foreign key be NULL EF core?

A foreign key is NULLABLE by DEFAULT in code first asp.net mvc - 5 entity framework. If we want to make it non nullable. we need to either use fluent api if not then decorate with "Required" attribute.

What is nullable field?

Nullable types are a feature of some programming languages which allow a value to be set to the special value NULL instead of the usual possible values of the data type.


1 Answers

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; } 
like image 138
danludwig Avatar answered Sep 22 '22 14:09

danludwig