简体   繁体   中英

How to specify composite relationships in EF code-first that don't map to PKs

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM