当外键列名不同时的实体框架映射

3

我有一个类似这样的遗留表:

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;}
2个回答

2

如果您的数据库列的类型是varchar(10),即使属性名与列名匹配或不匹配,您也不能在模型中使用int属性,而必须使用string。此外,为了能够从Store访问Country,您需要一个导航属性Store.Country

public class Country
{
    [Key]
    [Column("countryCode", TypeName = "varchar")]
    [MaxLength(10)]
    public string CountryCode { get; set; }
}

public class Store
{
    [Key]
    [Column("store_id")
    public int Id { get; set; }

    [Column("country_code", TypeName = "varchar")]
    [MaxLength(10)]
    [Required]
    [ForeignKey("Country")]
    public string CountryCode { get; set; }

    public virtual Country Country { get; set; }
}

可能 ForeignKey 属性不是必需的。您可以尝试在没有它的情况下运行。如果 Store 表中的 country_code 列允许 NULL 值,请删除 [Required] 属性。

现在,您应该能够通过以下方式访问 CountryCode

var store = context.Stores.Find(1);
string countryCode = store.Country.CountryCode;

当您访问该属性时,store.Country 导航属性将通过延迟加载(因此需要 virtual 修饰符)自动加载。


这个可以工作,谢谢,但是为什么我可以创建一个Store对象,保存它,即使我输入了一个虚假的countryCode。这似乎不是外键关系?如果PK行在Country表中不存在,它应该无法保存。 - loyalflow
当你在EF中使用[ForeignKey("Country")]属性时,CountryCode就是外键。如果你输入了一个无效的代码并尝试保存,假设数据库中也有外键参照约束,那么你应该会得到一个FK违规异常。 - Slauma

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接