Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I manually add a compound association in entity framework?

This seems like a common case, but for whatever reason, I am stymied by EF's weak editor.

I have two tables, like so:

Table1
(
Column1 int, PK
Column2 int, PK
)

Table2
(
Column1 int, PK, FK
Column2 int, PK, FK
Column3 int, PK
)

Now, the database (out of our control) does not have foreign key constraints. In this example, Table2 is supposed to have a foreign key constraint that references Table1 on (Column1, Column2). In other words, the first two columns of Table2 reference the primary key from Table1. This is an everyday issue in any ordinary database.

In other frameworks, such as LLBLGenPro, we can manually add the relation in a very trivial fashion. However, we cannot figure out how to achieve this in EF's editor. This "Mapping Details" window is awful and non-intuitive. So far, we have managed to select the various tables in the mapping, but it always seems to want to associate on all of the columns.

Any ideas or references?

like image 302
Pittsburgh DBA Avatar asked Feb 23 '09 22:02

Pittsburgh DBA


2 Answers

Assuming you have the two entities in place.

  1. Right click on Table1 entity header and select add association.
  2. Select Table2 from the right hand end. (Set any other properties in this wizard)
  3. Select the newly created association and edit the mapping. (Should already be selected)
  4. In the Mapping Details window, select Table2

That should be it.

like image 85
David McEwing Avatar answered Oct 11 '22 11:10

David McEwing


  1. Create "temporary" tables with same columns but proper FKs. Use a backup of the DB if you can't alter the "real" one. Don't bother mapping the tables without FKs. It may be easiest if you use a new model, as deleting in the designer doesn't remove store mappings.
  2. Map them with the wizard.
  3. Open the EDMX as XML (not in the designer)
  4. Search and replace the table names, using the tables you really want to map.
  5. Drop the "temporary" tables.

General advice: Edit EDMX manually when doing non-standard things. No FKs = non-standard. The GUI designer only handles certain cases.

like image 25
Craig Stuntz Avatar answered Oct 11 '22 12:10

Craig Stuntz