bryanjonker
bryanjonker

Reputation: 3406

EF Code First foreign key issue

I am using EF Code First to map to an existing DB2 database. This is a one-to-many relationship, and unfortunately I cannot easily create views or change the schema.

The schema for the parent table has the following keys:

 Type (char(1))
 ServiceDate (datetime)
 FormNumber (varchar(8))

The child table (Details) has the following keys

 ServiceDate (datetime) (also a foreign key to ServiceDate on the parent table)
 FormNumber (varchar(8)) (also a foreign key to ServiceDate on the parent table)
 SpecificServiceDate (datetime)
 LineNumber (varchar(8))

I'd like to use fluent mapping to create the relationship. If I do:

 .HasMany(e => e.Details).HasForeignKey(e => new {e.ServiceDate, e.FormNumber});

...I get an error saying the key does not match the primary key. Ideas on how to set this up? Thanks.

Edit

OK, EF doesn't natively support this. Is there a workaround to lazy-load the data?

This is for read-only, if that makes a difference.

Upvotes: 0

Views: 266

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

Unfortunately it is not possible. Relation in EF has same rules as in database. If your parent table has three columns in primary key your dependent table must have same three columns in foreign key.

I'm not sure if you can define such relation in DB2 without marking ServiceDate and FormNumber as unique key (in such case there would be no reason to have Type in PK as well) but you definitely can't define it in SQL server which is blue print for EF. Anyway EF currently doesn't support unique keys to form relation.

Upvotes: 1

Related Questions