Entity Framework 4.1 - Relationships between non-key columns

Tom Halladay picture Tom Halladay · Aug 24, 2011 · Viewed 8.7k times · Source

I have 2 entities that are related, but the legacy sql schema essentially has 2 key columns for the same table (not a 2-column key: see below). I need to create a relationship back to the 'faux key' column. Is there a way to do this declaratively in Entity Framework 4.1?

Public Class Client
    Inherits ModelBase

    <Key(), Required()>
    Public Property ClientID As Decimal

    <Required(), StringLength(50)>
    Public Property ClientCode As String

    ........


Public Class ClientLocation
    Inherits ModelBase

    ........

    <Required(), StringLength(50)>
    Public Property ClientCode As String

    ........

    <ForeignKey("ClientCode")>
    Public Overridable Property Client As Clients.Client

And the error I am getting is:

*One or more validation errors were detected during model generation: System.Data.Edm.EdmAssociationConstraint: : The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property 'ClientCode' on entity 'ClientLocation' does not match the type of property 'ClientID' on entity 'Client' in the referential constraint 'ClientLocation_Client'.*

Because it thinks I'm trying to map ClientLocation.ClientCode > Client.ClientID, when I am really trying to map ClientLocation.ClientCode > Client.ClientCode...

Any thoughts?

Thanks!

Answer

Ladislav Mrnka picture Ladislav Mrnka · Aug 24, 2011

Entity framework demands that relation is built between whole primary key in the principal table and corresponding columns (foreign key) it the dependent table.