0

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.

EZE
  • 69
  • 10

1 Answers1

0

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.

Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36
  • I would have to use the .computed to alter the database correct? If so I am unable to alter the database. – EZE Feb 08 '16 at 21:19
  • On the PS. I'm not sure what you are saying on it. I have 3 foreign keys for that entity. I've tried data annotation on those, but I still have the same issue since the 2 fields are [Not Mapped] – EZE Feb 08 '16 at 21:21
  • Sorry I forgot that you can't change the database. `Computed` tells EF that these values are generated by the database and it should not touch them. If you cant replicate the hard coded logic for T1: FK1 FK2 on the DB, this approach wont work. – Georg Patscheider Feb 08 '16 at 21:38
  • Sadly I'm not able too. If I could I would change the entire way this works :) – EZE Feb 09 '16 at 15:11