2012-01-18 92 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"); 
     } 
    );