Konrad Viltersten
Konrad Viltersten

Reputation: 39058

How to make EF understand that some columns are not nullable?

I've defined this fine table.

create table WeirdDonkey (
  Tails int not null,
  Heads int default 7
)

When I run EF on it, it creates two fields as follows.

public int Tails { get; set; }
public Nullable<int> Heads { get; set; }

Now, I do understand why it thinks that the number of heads is nullable but it doesn't make any sense. A donkey can't have null heads. It can have 7 if nothing else is specified. (Well, that doesn't make any sense zoologically speaking but let's pretend we're on a different planet that follows the rules of my SQL magic).

How can I make EF understand that the default is 7 and there'll be no null-headed donkeys?

Upvotes: 0

Views: 84

Answers (1)

sstan
sstan

Reputation: 36473

EF is right. Heads can have nulls. What happens if after inserting a row, you decide to update a Heads value to null. Will the database not accept it? Yes it will.

If you don't want nulls, you have to explicitly define it as such:

create table WeirdDonkey (
  Tails int not null,
  Heads int not null default 7
)

Upvotes: 4

Related Questions