Mikkel Mellum Hviid Mikkel Mellum Hviid - 28 days ago 7
C# Question

FK column to mulitple tables POCO

I'm trying to stay in POCO, but I'm at an impasse:

Public class Alpha()
{
public int ID { get; set; }
[ForeignKey("")]
public int BetaId { get; set; }

public virtual BetaA BetaA{ get; set; }
public virtual BetaB BetaB{ get; set; }
}

Public class BetaA()
{
public int ID { get; set; }
}

Public class BetaB()
{
public int ID { get; set; }
}


How do I get Alpha.BetaId to be both ForeignKey to BetaA.ID and BetaB.ID in POCO?

If anyone else stumble around this

Solution I used

Public class Alpha()
{
public int ID { get; set; }
public int BetaId { get; set; }

[ForeignKey("BetaId")]
public virtual BetaA BetaA{ get; set; }
[ForeignKey("BetaId")]
public virtual BetaB BetaB{ get; set; }
}

Public class BetaA()
{
public int ID { get; set; }
}

Public class BetaB()
{
public int ID { get; set; }
}

Answer Source

have BetaA and BetaB share a primary key then reference BetaB via BetaA

You can also decorate the nav properties with the foreign key attribute and specify the int property as the FK for both, though I have not tested this scenario myself (I'm on a mobile device). Give it a shot and let me know!