DeepSpace101
DeepSpace101

Reputation: 13722

Getting an Entity Framework 'navigation property' via a SQL Foreign Key relationship

I created a foreign key constraint between two of my SQL tables. Then I went into the the project's EDMX and selected "updated model from database". However my diagram shows NO lines between the tables nor are there any navigation properties on them. The only reason I care about the lines is because the lines, the navigation property and the EF understood relationships are all somehow tied together; and I don't want to screw with data integrity because EF had a different idea of the relationships.

Question: How does EF derive the navigation property from a database? If the state maintained inside SQL itself, what additional commands would I need to issue to the Azure SQL server to make it understand? Or do I have to modify the EDMX by hand?

Here is how I created the foreign key connecting the two tables

ALTER TABLE [dbo].[Employee]  
WITH CHECK ADD  CONSTRAINT [FK_Employee_Office_City] FOREIGN KEY([City])
REFERENCES [dbo].[Office] ([City])
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[Employee] CHECK CONSTRAINT [FK_Employee_Office_City]
GO

Important piece: The [City] column in the parent table (Office) isn't a primary key - it is however a UNIQUE INDEX column.

Also, we used EF code first initially but switched to database-first as the project grew. We had to regenerated the EDMX completely off the database at that switching point. And because the older tables still have nice navigation properties (post EDMX regeneration), that state must be stored somehow in the database for EF to recreate them. Just don't know how ...

Upvotes: 0

Views: 559

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364349

It will not work because EF doesn't understand unique keys. If you want to have mapped relationships the key in principal table must be primary key.

Upvotes: 1

Related Questions