2012-01-11 143 views
2

我用EF數據註解和我有類:實體框架 - 外鍵 - 數據註解

[Table("Accounts")] 
public class DbAccount 
{ 
    public int Id { get; set; } 
    public string Username { get; set; } 

    public virtual DbLicense License { get; set; } 
} 

[Table("Licenses")] 
public class DbLicense 
{ 
    public int Id { get; set; } 
    public int AccountId { get; set; } 

    [ForeignKey("AccountId")] 
    public virtual DbAccount Account { get; set; } 
} 

我該怎麼裝飾財產公共虛擬DbLicense許可{獲得;組; }

EF擲

無法確定類型「DbLicense」和「DbAccount」之間的關聯的主要端。該關聯的主要目的必須使用關係流暢API或數據註釋來顯式配置。

這項工作做得很好:

modelBuilder.Entity<DbAccount>() 
      .HasRequired(x => x.License) 
      .WithRequiredPrincipal(); 

但我怎麼能與標註使用寫的嗎?

回答

7

在配置一對一關係時,實體框架要求依賴項的主鍵也是外鍵。

試試這個:

[Table("Accounts")] 
public class DbAccount 
{ 
    [Key] 
    public int Id { get; set; } 
    public string Username { get; set; } 

    [InverseProperty("Account")] 
    public virtual DbLicense License { get; set; } 
} 

[Table("Licenses")] 
public class DbLicense 
{ 
    [Key, ForeignKey("Account")] 
    public int Id { get; set; } 
    public int AccountId { get; set; } 
    [InverseProperty("License")] 
    public virtual DbAccount Account { get; set; } 
} 
+0

請解釋一下,爲什麼你的解決方案比其他更好的,有什麼區別。 – gaborsch 2013-01-17 23:29:42

+0

因爲在配置一對一關係時,實體框架要求依賴項的主鍵也是外鍵。 – 2013-01-18 04:48:28

+0

挖掘> 1h後,這是最終的解決方案。恭喜。 – danihp 2014-02-11 11:17:13