EF add a foreign key from non PK columns to non PK columns

Viewed 9

I have a desktop application that needs to be implemented with a new function. Unfortunatly I cannot edit the database structure because there are other apps that rely on it.

The two following tables are already present in the db and I have a DbSet for both of them My goal is to create a property in Table1 DbSet like

public virtual ICollection<Table2> Table2 { get; set; }

so that for every Table1 object in the DbSet I have a Table2 property that stores all the Table2 associated objects.

Unfortunately, I tried with both DataAnnotation and Fluent API but I don't know how to exactly describe this.

I could leave the two DbSets alone and create joins in queries, but the existing code relies on Table1 objects and it would be easier to just add a property that "points" to Table2 to gain access to the required information.

Please note that:

  • The foreign key is composed of two fields
  • Field names are different in the two tables
  • There are no unique constraints on the fields, both on Table1 and Table2

.

+--------------------+      +--------------------+ 
| Table1             |      | Table2             |
+--+-----------------+      +--+-----------------+
|PK| Id              |      |PK| Id              |
|  | KeyToTab2Field1 |----->|  | Field1          |
|  | KeyToTab2Field2 |----->|  | Field2          |
|  | ...             |      |  | ...             |
+--+-----------------+      +--+-----------------+
0 Answers
Related