2012-01-11 15 views
2

私はEFでデータアノテーションを使用して、私はクラスの持っている:私は{取得財産パブリック仮想DbLicenseライセンスを飾る必要がありますどのようにエンティティフレームワーク - 外部キー - データ注釈

[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; } 
} 

を。セット; }

EFは

タイプ「DbLicense」と「DbAccount」との間の関連付けの主終了を決定することができませんを投げます。この関連付けの主な終点は、流暢なAPIまたはデータアノテーションのどちらかの関係を使用して明示的に構成する必要があります。

この作品も:

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

しかし、どのように私は使用して注釈でこれを書くことができますか?

答えて

7

1対1の関係を構成する場合、Entity Frameworkでは、依存関係の主キーも外部キーであることが要求されます。

代わりにこれを試してみてください:

[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

+0

1対1リレーションシップを構成する場合、Entity Frameworkでは、依存関係の主キーも外部キーになる必要があるためです。 –

+0

> 1時間掘削した後、これが最終的な解決策です。おめでとう。 – danihp

関連する問題