JakRuzL
JakRuzL

Reputation: 193

How to create relationships between entities with existing database that does not contain foreign keys

Using Entity Framework Core 2.0

Stuck with company's production database which has primary keys defined for each table but no foreign keys defined for any relationships.

Dependent records in the database have id fields which are intended to relate to the primary key fields of the parent record like you would normally find with a foreign key relationship/constraint. But these fields were all created as INT NOT NULL and are using a SQL default of '0'.

As a result dependent records have been inserted over time without requiring that a related parent record be specified.

Initially I defined my models in EF with integers and used a fluent configuration to specify "IsRequired". This was done so I could run migrations to create a test database for comparison against the production database to verify that my code first was correctly coded.

This then lead to the problem while using "Include" in my Linq queries which performs an inner join that results in dropping the records that contain the 0's in the id fields of the dependent record.

The only way that I have found to make this work is to model all of the id fields in the dependent entity as nullable integers and remove the "IsRequired" from the fluent configuration.

When using the "Include" it performs a left outer join keeping all of the dependent entities. This also means that any reference properties on the included entities are set to null instead of an empty string. This part can probably be fixed fairly easily.

The downside is if I wanted to use migrations to create a database now, all id fields in the dependent records would be created as NULL.

Is there anyone who has run up against this type of situation? Does anyone have any suggestions to try other than the approach I am using?

Upvotes: 3

Views: 973

Answers (1)

Julie Lerman
Julie Lerman

Reputation: 4622

I haven't dealt with this scenario before but I wonder if you can solve it by defining the FK property as Nullable and then in the migrations, after the migration is created, edit it to add a HasDefaultValue property to ensure that it's 0? (doc for that migration method: https://learn.microsoft.com/en-us/ef/core/modeling/relational/default-values)

Upvotes: 1

Related Questions