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

时间:2013-04-25 16:37:37

标签: c# entity-framework entity-framework-4.1

我有这样的遗产表:

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

如何创建此映射? 请注意,列名称不相同(我无法更改)。

我相信我必须将它添加到我的商店模型中,但是我如何具体说明因为它们有不同的名称而看到外键?

public virtual CountryCode {get;set;}

2 个答案:

答案 0 :(得分:2)

如果数据库列的类型为varchar(10),则无法在模型中使用int属性,但无论属性名称是否与列名匹配,都必须使用string或不。另外,为了能够从Country访问Store,您需要导航属性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属性可能不是必需的。您可以在没有它的情况下尝试。如果表[Required]中的country_code列允许,也可以删除Store属性NULL值。)

您现在应该可以访问CountryCode,例如:

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

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

答案 1 :(得分:0)

该名称与关联无关(尽管同名使db更直观)。通过emdx模型视图,可以使用一个表单来指定关联。

这是一个关于msdn的方便教程; http://blogs.msdn.com/b/efdesign/archive/2009/03/16/foreign-keys-in-the-entity-framework.aspx

相关问题