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:
Thanks!
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With