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

T1
[NotMapped]
FK1 {get {return "FOO"}}
[NotMapped]
FK2 {get {return "BAR"}}

Mapped this with fluent api

modelBuilder.Entity<T1>
    .HasRequired<T2>
    .WithMany()
    .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.

Answers


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

Search




Leave an answer