2012-01-18 97 views
1

我試圖描述映射到EF以下兩個實體之間建立多個許多一對多realtionships(簡體):實體Framwork - 多許多一對多的關係

產品:

public class Product 
    { 
     [Key] 
     public int ProductID { get; set; } 

     public string ProductName { get; set; } 
     public decimal Price { get; set; } 

     public virtual ICollection<Transaction> Transactions { get; set; } 
     public virtual ICollection<Transaction> RefundTransactions { get; set; } 
     public virtual ICollection<Transaction> VoidTransactions { get; set; } 
    } 

交易:

public class Transaction 
{ 
    [Key] 
    public int TransactionID { get; set; } 

    public virtual ICollection<Product> Products { get; set; } 
    public virtual ICollection<Product> RefundProducts { get; set; } 
    public virtual ICollection<Product> VoidProducts { get; set; } 
} 

OnModelCreating:

 modelBuilder.Entity<Transaction>() 
      .HasMany(m => m.Products) 
      .WithMany(t => t.Transactions) 
      .Map(m => 
      { 
       m.ToTable("Transaction_Product_Mapping"); 
       m.MapLeftKey("TransactionID"); 
       m.MapRightKey("ProductID"); 
      } 
     ); 

     modelBuilder.Entity<Transaction>() 
      .HasMany(transaction => transaction.VoidProducts) 
      .WithMany(t => t.VoidTransactions) 
      .Map(m => 
      { 
       m.ToTable("Transaction_Void_Product_Mapping"); 
       m.MapLeftKey("TransactionID"); 
       m.MapRightKey("VoidProductID"); 
      } 
     ); 

     modelBuilder.Entity<Transaction>() 
      .HasMany(m => m.RefundProducts) 
      .WithMany(t => t.Transactions) 
      .Map(m => 
      { 
       m.ToTable("Transaction_Refund_Product_Mapping"); 
       m.MapLeftKey("TransactionID"); 
       m.MapRightKey("RefundProductID"); 
      } 
     ); 

例外:

Type Transaction_Products is not defined in namespace Nautix_EPOS.Models 

現在,我想這可能是因爲我seperately定義映射的3倍。並可能用第二個覆蓋第一個,用第二個覆蓋第二個。

問:

我怎麼能告訴EF差不多的兩個表之間的多個許多一對多映射?

回答

1

我想通了,這是因爲我在第一個和第三個聲明中使用了相同的t.Transactions。我應該使用t.RefundTransactions

modelBuilder.Entity<Transaction>() 
     .HasMany(m => m.Products) 
     .WithMany(t => t.Transactions) 
     .Map(m => 
     { 
      m.ToTable("Transaction_Product_Mapping"); 
      m.MapLeftKey("TransactionID"); 
      m.MapRightKey("ProductID"); 
     } 
    ); 

    modelBuilder.Entity<Transaction>() 
     .HasMany(transaction => transaction.VoidProducts) 
     .WithMany(t => t.VoidTransactions) 
     .Map(m => 
     { 
      m.ToTable("Transaction_Void_Product_Mapping"); 
      m.MapLeftKey("TransactionID"); 
      m.MapRightKey("VoidProductID"); 
     } 
    ); 

    modelBuilder.Entity<Transaction>() 
     .HasMany(m => m.RefundProducts) 
     .WithMany(t => t.RefundTransactions) 
     .Map(m => 
     { 
      m.ToTable("Transaction_Refund_Product_Mapping"); 
      m.MapLeftKey("TransactionID"); 
      m.MapRightKey("RefundProductID"); 
     } 
    );