Appetere
Appetere

Reputation: 6261

Map required field to nullable in database

I have an Entity Framework code-first model in which a Supplier must always have a SupplierGroup:

    public virtual SupplierGroup SupplierGroup { get; set; }
    public int SupplierGroupId { get; set; }

But the underlying database has to have SupplierGroupId as nullable (due to another system using it, in which a Supplier can exist without a SupplierGroup).

Is there any way to make Entity Framework generate/map to a nullable database-field, but otherwise continue to treat the field in the model as required?

I tried a fluent mapping:

modelBuilder.Entity<Supplier>()
     .Property(s => s.SupplierGroupId)
     .IsOptional();

But when code-first generated the database, the field was still not nullable.

(If a Supplier without a SupplierGroup was ever requested, this should throw an exception as it should never happen).

Upvotes: 2

Views: 1478

Answers (1)

Slauma
Slauma

Reputation: 177153

It's impossible to create the database with Entity Framework with the default database initializers in a way that an int property would result in a nullable column. As far as I can see your options are:

  1. Write a custom database initializer that executes a SQL script which changes the column from not-nullable to a nullable column

  2. Don't create the database with Entity Framework, but manually instead (by setting the database initializer to null for example), having a nullable column and a not-nullable property

  3. Treat your requirement as application specific business logic that is not reflected in the database (and can't be because other applications accessing the DB have the requirement to allow NULLs), i.e. make the property int? and ensure in your application that null is never used

For option 1 and 2 your model is "out of sync" with the database which would mean that you'll get exceptions when you load a Supplier from the database whose SupplierGroupId is NULL (probably something like "...cannot store materialized value NULL in non-nullable property...").

I would choose option 3.

Upvotes: 3

Related Questions