1

我已經使用通用存儲庫模式設置了實體框架代碼。數據庫未被正確自動生成實體框架+回購模式

這裏是我的模型:

public interface IEntity { 
    int Key { get; set; } 
} 

public class Product : IEntity { 
    public int Key { 
     get { 
      return ID; 
     } 
     set { 
      ID = value; 
     } 
    } 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public decimal Price { get; set; } 
    public IEnumerable<Category> Category { get; set; } 

} 

public class Category : IEntity { 
    public int Key { 
     get { 
      return ID; 
     } 
     set { 
      ID = value; 
     } 
    } 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public int ParentID { get; set; } 

} 

這裏是我的背景下,掛鉤到我的通用回購:

public class EntitiesContext : DbContext, IDbContext { 

    public DbSet<Product> Products { get; set; } 
    public new IDbSet<T> Set<T>() where T : class { 
     return base.Set<T>(); 
    } 
} 

正如你可以看到產品具有類別的IEnumerable的。如果我要建立一個數據庫,以配合這會是像這樣:

產品 - ID - 名稱 - 等

類別 - ID - 名稱 - 等。

ProductCategories - 產品ID - 類別ID

當我的數據庫被創建時沒有連接表怎麼發生?

enter image description here

回答

1

我敢肯定那是因爲你所定義的集合作爲IEnumerable<T>。我認爲實體框架至少需要一個ICollection<T>來建立關係。 This SO post涵蓋了大部分。另外

public ICollection<Category> Category { get; set; } 

,如果你想延遲加載的集合,然後又讓它虛:

因此,改變這種:

public IEnumerable<Category> Category { get; set; } 

對此

public virtual ICollection<Category> Category { get; set; } 
+0

你'對了,它工作。我還加入了公開ICollection 產品{get;組; }到我的類別模型來創建正確的表和關係。附:謝謝你的懶惰加載提示也:) – Smithy 2013-03-08 09:22:32

+0

實際上,在我的視圖模型(這些是我的DTOs)我應該繼續使用Icollection的棍子Ienumerable或無所謂? – Smithy 2013-03-08 09:23:19

+1

我建議儘可能使用「最輕」的對象。因爲ICollection從IEnumerable繼承,所以你應該能夠從ICollection中設置IEnumerable。所以,選擇取決於你。如果您將索引編入集合,則「ICollection」效率更高。 – 2013-03-08 09:27:42