Home Ask Login Register

Developers Planet

Your answer is one click away!

EZE February 2016

How to use NotMapped Properties in a Composite Foreign Key

I'm creating a Codefirst from database EF project. The database this is being generated from I am unable to alter in anyway. I have manually created most of the relationships between the tables, however I have hit a wall with a table.

Have two tables

T1: FK3
T2: PK1 PK2 PK3

The relationship between T1: FK1 FK2 is Hard coded logic. Because the Table is T1 then FK1 = "Foo" and FK2 = "BAR"

I've created

FK1 {get {return "FOO"}}
FK2 {get {return "BAR"}}

Mapped this with fluent api

    .HasForeignKey(f => new {f.FK1, f.FK2, f.FK3 })

I get the error:

The foreign key component 'FK1' is not a 
declared property on type 'T1'. Verify that it has not been     
explicitly excluded from the model and that it is a valid primitive property.

How can I create this relationship? I've tried DataAnnotations fluentapi doesn't seem to handle it.


Georg Patscheider February 2016

You can't use [NotMapped] properties as keys. Not mapped means exaclty that - "this is c# code that wont be mapped to the database".

You can however use [DatabaseGenerated(DatabaseGenerationOption.Computed)] and calculate the values on the database : custom sequence string as sql identity column

PS.: The hazzle free way to declare a foreign key is [ForeignKey] and just use an int to hold the ids.

Post Status

Asked in February 2016
Viewed 2,152 times
Voted 7
Answered 1 times


Leave an answer

Quote of the day: live life