2015-04-23 112 views
1

一對多的關係我有2類Foo和Bar實體框架多很多使用代碼首先

public class Foo 
    { 
     [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
     public virtual int Id { get; set; } 


     private ICollection<Bar> _bar; 
     public virtual ICollection<Bar> Bars 
     { 
      get { return _bar?? (_bar= new Collection<Bar>()); } 
      set { _bar= value; } 
     } 
    } 

酒吧

public class Bar 
     { 
      [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
      public virtual int Id { get; set; } 


      private ICollection<Foo> _foo1; 
      public virtual ICollection<Foo> Foos1 
      { 
       get { return _foo1?? (_foo1= new Collection<Foo>()); } 
       set { _foo1= value; } 
      } 

       private ICollection<Foo> _foo2; 
       public virtual ICollection<Foo> Foos2 
       { 
        get { return _foo2?? (_foo2= new Collection<Foo>()); } 
        set { _foo2= value; } 
       } 


      } 

然後我使用遷移來更新數據庫。但是,而不是有一個通常的表FooBar。 EF創建2個表格

Foo 
Id,Bar_Id 

Bar 
Id,Foo_Id,Foo_Id1 

這不是我想要的。我想我通過將2個Foo的集合添加到Bar中來搞砸了。我現在應該怎麼做?

+0

那麼,爲什麼你有2個集合?你想達到什麼目的? –

+0

因爲這是我必須應用的業務規則。考慮一種含有兩種稅種的物品,因此您將購買稅(在您購買物品時適用的稅)和銷售稅(在銷售物品時將適用稅)。現在你問,也許我的模型不太好,有什麼建議嗎? – Quannt

回答

1

想通了,我需要做2件事來解決這個問題。首先,添加酒吧的另一個集合的Foo

public class Foo 
     { 
      [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
      public virtual int Id { get; set; } 


      private ICollection<Bar> _bar; 
      public virtual ICollection<Bar> Bars 
      { 
       get { return _bar?? (_bar= new Collection<Bar>()); } 
       set { _bar= value; } 
      } 

      private ICollection<Bar> _bar2; 
      public virtual ICollection<Bar> Bars2 
      { 
       get { return _bar2?? (_bar2= new Collection<Bar>()); } 
       set { _bar2= value; } 
      } 
     } 

二,使用InverseProperty明確地告訴我要2個多一對多的關係EF。

public class Bar 
     { 
      [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
      public virtual int Id { get; set; } 


      private ICollection<Foo> _foo1; 
      [InverseProperty("Bars")] 
      public virtual ICollection<Foo> Foos1 
      { 
       get { return _foo1?? (_foo1= new Collection<Foo>()); } 
       set { _foo1= value; } 
      } 

       private ICollection<Foo> _foo2; 
       [InverseProperty("Bars2")] 
       public virtual ICollection<Foo> Foos2 
       { 
        get { return _foo2?? (_foo2= new Collection<Foo>()); } 
        set { _foo2= value; } 
       } 


      } 

我現在有4臺富,酒吧,FooBarss和FooBar1

最終