我有一个类似这样的遗留表:
Country
- countryCode (PK, varchar(10), not null)
现在我有一张新的表格:
Store
- store_id
- country_code
我的模型:
public class Country
{
[Key]
[Column("countryCode")
public int CountryCode {get;set;}
}
public class Store
{
[Key]
[Column("store_id")
public int Id {get;set;}
[Column("country_code")]
public int CountryCode {get;set;}
}
现在我希望能够做到这一点:
var store = // get store
store.Country.CountryCode
我该如何创建这个映射关系?请注意列名不同(我无法更改)。
我相信我必须将其添加到我的Store模型中,但由于它们具有不同的名称,我该如何指定外键?
public virtual CountryCode {get;set;}
[ForeignKey("Country")]
属性时,CountryCode
就是外键。如果你输入了一个无效的代码并尝试保存,假设数据库中也有外键参照约束,那么你应该会得到一个FK违规异常。 - Slauma