2012-04-23 19 views
1
[Table("Table1")] 
    public class Entity1 
    { 
     [Key, ForeignKey("entity1")] 
     public int ID{get;set;} 
     public virtual Entity2 entity2{get;set;} 
     public virtual Entity3 entity3{get;set;} 
    } 


これは私の主なエンティティです。ここでは、このEntityをEntity2と3とにマッピングする場合、Entity1,2,3の主キーでもある同じ外部キーを使用したいと考えています。

EFで共有する外部キーを使用する方法

[Table("Table2")] 
    public class Entity2 
    { 
     [Key] 
     public int Entity1ID{get;set;} 
     // few entity specific properties 
    } 


[Table("Table3")] 
    public class Entity3 
    { 
     [Key] 
     public int Entity1ID{get;set;} 
     // few entity specific properties 
    } 


マッピングのための私のコンテキストクラスを使用した場合、私はエラーが表示さthe Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must

答えて

2
modelBuilder.Entity<Entity1>().HasOptional(u => u.Entity2) 
          .WithRequired(); 
     modelBuilder.Entity<Entity1>().HasOptional(u => u.Entity2) 
          .WithRequired(); 


あなただけの共有プライマリキーの関係が必要な場合は、行うには、余分なものは何もありません上記のコードを使用するので、注釈の属性を削除します。

-1

はあなたが同じ名前を持つ2つのプロパティを持つことができないと言います。ところで

[Table("Table1")] 
public class Entity1 
{ 
    [Key, ForeignKey("Entity2"), ForeignKey("Entity3")] 
    pubic int ID{get;set;} 
    public virtual Entity2 Entity2{get;set;} 
    public virtual Entity3 Entity3{get;set;} 
} 

:これを試してみてください。それは非常に奇妙なデザインのように見えます。

+0

エラー:重複する外部キー属性 – RollerCosta

+0

私の質問が更新されました – RollerCosta

+0

そのような場合、属性の代わりにFluent APIを使用してみてください。 –

関連する問題