2017-01-09 6 views
1

Entity Frameworkを使用して複数のデータテーブルにEntity-Attribute-Value機能を実装する必要があります。複数のテーブル/エンティティへのEntity Framework外部キー

public class EntityAttributeValue 
{ 
    // Not important to my question. 
    public virtual Entity ParentEntity { get; set; } 
    public virtual EntityAttribute ParentEntityAttribute { get; set; } 

    // Field in question. 
    public Guid ParentSurrogateKey { get; set; } 

    public string Value { get; set; } 

    ... 
} 

は、その後、私はそれらに関連付けられている補助的なEAV値を持つ複数のエンティティを持っている:のは、私はこのようになります属性値EFクラスがあるとしましょう

public class Entity1 
{ 
    // Key. EntityAttributeBalue.ParentSurrogateKey maps to this. 
    [Key] 
    public Guid SurrogateKey { get; set; } 

    // Standard properties. 
    public string Property1 { get; set; } 
    public string Property2 { get; set; } 

    // Collection of EAV values associated with this entity/table. 
    [ForeignKey("ParentSurrogateKey")] 
    public virtual IList<EntityAttributeValue> EntityAttributeValues { get; set; } 
} 

public class Entity2 
{ 
    // Key. EntityAttributeBalue.ParentSurrogateKey maps to this. 
    [Key] 
    public Guid SurrogateKey { get; set; } 

    // Standard properties. 
    public string OtherProperty1 { get; set; } 
    public string OtherProperty2 { get; set; } 

    // Collection of EAV values associated with this entity/table. 
    [ForeignKey("ParentSurrogateKey")] 
    public virtual IList<EntityAttributeValue> EntityAttributeValues { get; set; } 
} 

私の問題は、Entity1とEntity2両方EntityAttributeValueオブジェクトが関連付けられています。コードの最初の移行では、EntityAttributeValueからEntity1への外部キーの作成を試み、もう1つはParentSurrogateKeyのEntity2への外部キーの作成を試みます。任意の単一のEntityAttributeValueの代理キーは、Entity1またはEntity2のいずれか(または、1つのEntityN ...)に関連付けられています。

ここには多対多の関係がありますが、片側は複数の行にマッピングされるだけでなく、共有GUID列に複数のエンティティ/テーブルがマッピングされます。

これにどのようにアプローチすればよいですか? EntityAttributeValueの外部キーをEntity1とEntity2に戻して、自動移行(長期的な苦痛になるでしょう)から削除するだけですか? EFに依存するのではなく、特定のEAVエンティティのEntityAttributeValuesのリストを手動で取得する必要がありますか?

+1

これは基本的なEF初心者の質問だったと思います。実際に多対多として設定すると、自動的に作成されたジョイン・テーブルがその状況を処理します。私はそれを試みたと思ったが、明らかにそうではなかった。これがうまくいくなら、私は自分の質問に答えます。 –

答えて

1

まあ、答えは明白で簡単であることが判明しました。私はFluentAPIと多対多の関係を定義する必要がありました。 OnModelCreatingでは、私はちょうど追加:

  modelBuilder.Entity<Entity1>() 
       .HasMany(m => m.EntityAttributeValues) 
       .WithMany(); 

      modelBuilder.Entity<Entity2>() 
       .HasMany(m => m.EntityAttributeValues) 
       .WithMany(); 

私はこれを試したと思ったが、私はいなかったと思います。多対多関係は各エンティティの中間テーブルを作成し、外部キーはその中間テーブルに存在するため(与えられたEntityAttributeValueが特定のEntityに適用されるときに中間テーブルに行が存在するだけです)、外部キーの問題はありません。

+0

私の混乱の理由の1つは、与えられたEntityAttributeValuesオブジェクトに対して常に1つのEntityNオブジェクトがあるということでした。しかし、異なるEntityAttributeValuesインスタンスは異なるタイプ(クラス)のEntityNオブジェクトにマップできるため、多くの場合と多くの場合の関係を表すことは、問題を避けるための短所です。おそらく、この戦略が「クルジー」と見なされる可能性があります。 –

関連する問題