1

如何在 EF 中定义具有不同主键和外键名称的一对多关系
更新

Public class Tb1
{
[Key]
public int ID{get; set;}         // primary
**public int foreignKey{get; set;} //foreign key**
public string name{get; set;} 
[Foreign("foreignKey")]
public virtual ICollection<Tb2> Tb2{ get; set; }
}

Public class Tb2
{
[Key]
public int ID {get; set;} //primary
public int tb1ID {get; set}
public string address {get; set;} 
}


在这里,我想要主键上的一对多关系:外键在 TB1
外键:tb1ID 在 TB2
如何?

4

1 回答 1

1

我的 Nomal 方法也是包含导航属性。所以我会像这样改变 Tb2:

Public class Tb2
{
  [Key]
  public int ID {get; set;} //primary
  public int Tb1ID {get; set;} //notice I changed case on this variable as well
  public Tb1 Tb1 {get; set;} //this is the new variable
  public string address {get; set;} 
}

Code first 现在应该能够自动理解这种关系。如果您不想要 Tb1ID 属性,您可以删除它,它仍然可以正常工作。

于 2012-04-20T06:48:34.997 回答