m.edmondson
m.edmondson

Reputation: 30882

Define composite primary key in Entity Framework

I have a table which has no primary key defined. When adding this to my DataModel the tool generates the following message:

Errors Found During Generation:
warning 6013: The table/view 'CHARGE_DETAILS' does not have a primary key defined and no valid primary key could be inferred. This table/view has been excluded. To use the entity, you will need to review your schema, add the correct keys, and uncomment it.

I cannot modify the table in any way - however I reckon I could construct a composite key from two columns in order to satisfy these requirements.

However it appears that within the EntityType element Key can only contain zero or one elements.

So how would I instruct EF to treat two columns as a key?

Upvotes: 0

Views: 1588

Answers (2)

flindeberg
flindeberg

Reputation: 5017

I had the same problem today, I did a quick and dirty to get it working. I just commented out the defining query in the .edmx-file for the given entity.

"Original":

<EntitySet Name="CODES" EntityType="Self.CODES" store:Type="Tables" store:Schema="PIZZA">
  <DefiningQuery>
   SELECT 
    "CODES"."LINE" AS "LINE", 
    "CODES"."TEXT" AS "TEXT", 
    "CODES"."MODULE" AS "MODULE", 
    "CODES"."DEFAULT" AS "DEFAULT"
  </DefiningQuery>
</EntitySet>

After modification:

<EntitySet Name="CODES" EntityType="Self.CODES" store:Type="Tables" store:Schema="PIZZA">
  <!--<DefiningQuery>
   SELECT 
    "CODES"."LINE" AS "LINE", 
    "CODES"."TEXT" AS "TEXT",
    "CODES"."MODULE" AS "MODULE", 
    "CODES"."DEFAULT" AS "DEFAULT"
  </DefiningQuery>-->
</EntitySet>

In my case this worked, but I assume it does not work in every case. I'm using LINE and MODULE as a composite key. I'm not doing anything fancy with this table, just raw inserts, so it works.

Upvotes: 1

HamoriZ
HamoriZ

Reputation: 2438

You can create composite primary key on the database side. Do you use ODP.Net? It will automatically map your database pk.

Upvotes: 1

Related Questions