[英]Entity framework mapping when foreign key column name is different
我有一个像这样的遗留表:
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;}
如果数据库列的类型为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
修饰符)自动加载。
该名称与关联无关(尽管同名使db更直观)。 通过emdx模型视图,可以使用一个表单来指定关联。
这是一个关于msdn的方便教程; http://blogs.msdn.com/b/efdesign/archive/2009/03/16/foreign-keys-in-the-entity-framework.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.