0

I asked this ages ago but worded the question badly.

I'm trying to specify a relationship between 2 classes that isn't a simple FK mapping - this is a pre-existing database, not something I will generate from EF.

So, a simplified view of the 2 objects:

public class WidgetDetails
{

    [Key]
    public int WidgetId { get; set; }

    public int WidgetNumber {get; set;}

    // Some other props here..

    [ForeignKey("WidgetId,WidgetNumber")]
    public virtual WidgetProps WidgetProps { get; set; }


}

public class WidgetProps
{
    [Key]
    public int WidgetPropId { get; set; }

    [Key, Column(Order = 0)]
    public int WidgetId { get; set; }

    [Key, Column(Order = 1)]
    public int WidgetNumber { get; set; }

    // Some props here...
}

The key thing here is that WidgetProps already has it's own PK. BUT - because I want to be able to specify that WidgetProps are related to WidgetDetails using the composite WidgetId and WidgetNumber, I try to specify that in my ForeignKey attribute.

HOWEVER, that will only work if I remove the [KEY] attribute from the WidgetProps.WidgetPropId - because in EF the relationships are mapped using keys.

What I want to say to EF is "Hey, this is the PK column, but this relationship is not using it, it's based on these 2 columns".

Is this possible?

Hope that makes sense!

Community
  • 1
  • 1
Matt Roberts
  • 26,371
  • 31
  • 103
  • 180

1 Answers1

2

It is not possible. EF can create only relations which follow database rules. FK on dependent side must contain all parts of PK on principal side.

General rule: EF fluent API is not able to define any relationship which you cannot define in database by using PK, FK relationship.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Looks like the only way I can do this then is to add properties that represent the relationship and fetch the related data from the db. Thanks for the clarification! – Matt Roberts Feb 08 '12 at 08:21