2013-04-25 93 views
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

如果你的數據庫列的類型爲varchar(10)你不能使用你的模型的int屬性,但如果該屬性名相匹配的列名或沒有,你必須使用一個string,不管。另外,爲了能夠訪問來自你需要一個導航屬性Store.CountryStoreCountry

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]屬性。如果在表Storecountry_code列允許NULL值)

您應該能夠現在訪問CountryCode例如:

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

當您訪問屬性時,store.Country導航屬性將通過延遲加載(因此爲virtual修飾符)自動加載。

+0

這個作品謝謝,但我怎麼能創建一個Store對象,保存它,即使當我把一個假的countryCode。它似乎不是一個外鍵關係?如果國家/地區表中不存在PK行,它將無法保存。 – loyalflow 2013-04-25 18:25:03

+0

@ user1361315:當您爲EF使用'[ForeignKey(「Country」)]屬性時,CountryCode是外鍵。如果您輸入了無效的代碼並嘗試保存,則應該得到FK違例異常,假定數據庫中還存在外鍵參照約束。 – Slauma 2013-04-25 18:36:34