Reputation: 4832
I am trying to describe the mapping to EF to create multiple many-to-many relationships between the following two entities (simplified):
Product:
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; }
}
Transaction:
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");
}
);
Exception:
Type Transaction_Products is not defined in namespace Nautix_EPOS.Models
Now, I think this may be because I am defining the mapping 3 times separately. And possibly overwriting the first with the second, and the second with the last.
Question:
How can I tell EF about the multiple many-to-many mappings between the same two tables?
Upvotes: 1
Views: 886
Reputation: 4832
I figured it out, it's because I used the same t.Transactions
in the first and third declaration. I should have use 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");
}
);
Upvotes: 1