Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Database First - Composite Foreign Keys

I have a database that contains a couple of composite foreign keys. For example, here is the generation script for the foreign key:

ALTER TABLE [dbo].[WorkingRosters]  WITH NOCHECK ADD  CONSTRAINT
[FK_WorkingRoster_ShiftLeaveCode] FOREIGN KEY([OrganizationID], [ShiftLeaveCode])
REFERENCES [dbo].[ShiftLeaveCodes] ([OrganizationID], [Code])
GO

I am attempting to use Entity Framework 5 Database-First to generate a model from this database. However, the associations for the composite foreign keys are not being generated with all the tables and other simple foreign keys.

How can I either:

  1. manually create these composite foreign keys in the xml behind the edmx (painful)
  2. have entity framework properly generate these foreign keys so that I have have the mappings

Thanks!

like image 312
Bo Rohlfsen Avatar asked Nov 28 '12 00:11

Bo Rohlfsen


People also ask

Can foreign key be composite?

A composite key specifies multiple columns for a primary-key or foreign-key constraint. The next example creates two tables. The first table has a composite key that acts as a primary key, and the second table has a composite key that acts as a foreign key.

How do you set a foreign key in code first approach?

To create Foreign Key, you need to use ForeignKey attribute with specifying the name of the property as parameter. You also need to specify the name of the table which is going to participate in relationship.

How do I create a composite primary key in Entity Framework Core?

Entity Framework Core supports composite keys - primary key values generated from two or more fields in the database. Composite keys are not covered by conventions or data annotation attributes. The only way to configure composite keys is to use the HasKey method.

What is primary composite and foreign key?

A key which has multiple attributes to uniquely identify rows in a table is called a composite key. An artificial key which aims to uniquely identify each record is called a surrogate key. Primary Key never accept null values while a foreign key may accept multiple null values.


1 Answers

Entity Framework Database First doesn't behave with unique keys as you need. If you want them to be navigation properties, you should set them as foreign keys.

Now, you have to choice: 1) you just need NavPrs, 2) You also need the junction table as an entity.

1) To achieve this, just set those foreign keys as a composite primary key.

2) To achive this, leave them as foreign keys and declare an identity type ID column for your junction table and set it as the primary key.

This should work for you

like image 144
Amin Saqi Avatar answered Oct 02 '22 05:10

Amin Saqi