Marina Melin
Marina Melin

Reputation: 172

EF Code First change data type bool? to bool and int? to int

We have an application where we use Automatic Data Migrations, and Data Loss is not allowed. By company's policy, I am not allowed to change those settings.

We also have a few nullable columns in a few tables of bool? type and int? type.

I just discovered today that there is a piece of code which goes over existing database records and sets values of nullable columns to their default values (false and 0 respectively). Current behavior slows down the application. I want to enforce the database/EF to set default values and not allow nulls.

So far I tried the following with no luck:

  1. Direct type change from bool? to bool and int? to int. It throws Data Loss Exception.
  2. Adding [Required] and [DefaultValue(false)] attributes over a nullable property. Same thing, Data Loss Exception.
  3. Changing .IsOptional() to .IsRequired() in the mapping class also caused same exception.

What I essentially want to replicate in Code First EF is a following MySQL statement:

ALTER TABLE orders 
CHANGE COLUMN ScaleToFit ScaleToFit TINYINT(1) NOT NULL DEFAULT 0;

Are there any elegant solutions for the problem with respect to company's policy? Thank you!

Upvotes: 1

Views: 1155

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109253

This may be my first non-programming answer.

I most sincerely hope there's no elegant solution --and no solution at all-- to achieve this through migrations. It would mean there's a leak in data loss detection, which would be bad news. It's considered data loss because a null value may also bear information, i.e. a deliberate "don't know". In case of a boolean: three-state is turned into two-state. This isn't true in your case, hence this fixing process, but that doesn't change the rule.

By company's policy, I am not allowed to change those settings.

Policies serve a purpose, but nearly always turn into the purpose. Probably because policies are easier to define, enforce and check than their underlying purpose. But as in Goodhart's law...

When a measure becomes a target, it ceases to be a good measure

...each policy may one day defeat its purpose and cease to be a good policy. An ability to recognize this and to flex on policies when necessary is a commendable feature of organizations.

What I'm trying to say is: propose a temporary one-time suspension of this policy to allow for a migration that only applies these non-nullable fields with default values. If the null values are really meaningless and actually should have been not-null from the outset this is the easiest way to get where you want.

Upvotes: 3

Related Questions