2012-09-07 44 views
2

我有一個多對多的關係,我想添加一箇中間類,這將使我能夠使用存儲庫模式添加多對多關係。我想不出的是映射。多對多實體框架代碼中的中間對象映射

這裏的結構

public class Product 
{ 
    public Product() 
    { 
     Categories = new HashSet<Category>(); 
    } 

    public int Id { get; set; } 
    public string Name { get; set; } 

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

public class Category 
{ 
    public int Id { get; set; } 
    public String Name { get; set; } 

    public ICollection<Product> Products { get; set; } 

} 

public class PCMap 
{ 
    public int product_id { get; set; } 
    public int category_id { get; set; } 

    public Product Product { get; set; } 
    public Category Category { get; set; } 
} 

和映射

modelBuilder.Entity<Product>() 
    .HasEntitySetName("PCMap") 
    .HasMany(p=>p.Categories) 
    .WithMany(p=>p.Products) 
    .Map(m=> 
     { 
      m.MapLeftKey("product_id"); 
      m.MapRightKey("category_id"); 
      m.ToTable("PCMap"); 
     }); 

modelBuilder.Entity<PCMap>() 
    .ToTable("PCMap"); 

modelBuilder.Entity<PCMap>().HasKey(k => new 
    { 
     k.category_id, 
     k.product_id 
    }); 

modelBuilder.Entity<PCMap>() 
    .HasRequired(p=>p.Product) 
    .WithMany() 
    .HasForeignKey(p => p.product_id); 

modelBuilder.Entity<PCMap>() 
    .HasRequired(p => p.Category) 
    .WithMany() 
    .HasForeignKey(p => p.category_id); 

下面是我的錯誤.. 我該如何解決這個問題?

enter image description here

回答

3

你設置它的方式。 PCMap是一個非實體,僅用於促進引擎蓋下的M:N連接。

Product p = new Product(); 
p.Categories ... 

Category c = new Category(); 
c.Products ... 

因此,您可能已經將PC定義爲產品實體定義的一部分。

.Map(m=> 
     { 
      m.MapLeftKey("product_id"); 
      m.MapRightKey("category_id"); 
      m.ToTable("PCMap"); 
     }); 

我不相信你需要(或者有可能)再次定義它,分別在下面。嘗試刪除所有此代碼。

modelBuilder.Entity<PCMap>() 
    .ToTable("PCMap"); 
modelBuilder.Entity<PCMap>().HasKey(k => new 
    { 
     k.category_id, 
     k.product_id 
    }); 

modelBuilder.Entity<PCMap>() 
    .HasRequired(p=>p.Product) 
    .WithMany() 
    .HasForeignKey(p => p.product_id); 

modelBuilder.Entity<PCMap>() 
    .HasRequired(p => p.Category) 
    .WithMany() 
    .HasForeignKey(p => p.category_id); 
+0

是的,刪除此代碼,消除錯誤。我的問題是 - 我需要訪問該表格(PCMap)。我想要的是能夠直接實例化PCMap實例並將其保存到DB – Marty

+1

啊。然後你不想像你所做的那樣創建映射。 取而代之,您希望建立類似 'Product.PCMaps.Categories'和'Category.PCMaps.Products'的關係。 我不認爲你可以雙方面。 –

+3

您不能將實體作爲交接點並維護直接導航屬性。見[這篇文章](http://stackoverflow.com/questions/5418155/many-to-many-relationship-with-junction-table-in-entity-framework) –

相關問題