Ho due oggetti con molte e molte relazioni:
public class Order
{
public int OrderID { get; set; }
public string OrderName { get; set; }
public virtual Collection<Product> Products { get; set; } = new Collection<Product>();
}
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public int OrderID { get; set; }
public virtual Collection<Order> Orders { get; set; } = new Collection<Order>();
}
// Mapping table
public class OrderProduct
{
public int OrderId { get; set; }
public Order Order { get; set; }
public int ProductId { get; set; }
public Product Product { get; set; }
}
Vorrei aggiungere un nuovo ordine con una raccolta di prodotti esistenti (la mia API avrebbe un input di array ProductID) nel database, quindi mi comporto come:
private void AddOrder(int[] productIDs)
{
Order newOrder = new Order();
newOrder.Name = "New Order";
// Here I have no clue which would be the correct way...Should I do
// Approach A(fetch each related entity - Product from database then add them into the collection of my new base entity - Order):
productIDs.ToList().Foreach(p =>
{
newOrder.Products.Add(_dbContext.Product.FindById(p))
}
);
_dbContext.Orders.Add(newOrder);
var newOrderID = _dbContext.SaveChanges();
// then fetch each product from database and add my new Order to its collection and save
productIDs.ToList().Foreach(p =>
{
var existedProductFromDb = _dbContext.Product.FindById(p)ï¼›
existedProductFromDb.Orders.Add(newOrder);
_dbContext.SaveChanges();
}
);
}
Ho davvero bisogno della tabella di mappatura tra ordine e prodotto in Entity Framework Core? Altrimenti, quale sarebbe il modo corretto di trattare lo scenario sopra?
Le tue entità non rappresentano una relazione molti-a-molti utilizzando una tabella unita. In realtà, non si usa affatto il tavolo di congiunzione.
Quindi, inizia risolvendo le tue entità:
public class Order
{
public int OrderID {get;set;}
public string OrderName {get;set;}
public ICollection<OrderProduct> Products { get; set; } = new HashSet<OrderProduct>();
}
public class Product
{
public int ProductID {get;set;}
public string ProductName {get;set;}
public ICollection<OrderProduct> Orders { get; set; } = new HashSet<OrderProduct>();
}
Un nuovo Order
che contiene molti Product
è semplice come una raccolta di nuovi prodotti OrderProduct
:
private void AddOrder(int[] productIDs)
{
Order newOrder = new Order();
newOrder.Name = "New Order";
foreach (int productId in productIDs)
{
newOrder.Products.Add(new OrderProduct { ProductId = productId });
}
_dbContext.Orders.Add(newOrder);
_dbContext.SaveChanges();
}
Inoltre, si noti che SaveChanges
restituisce il numero di righe interessate nel database, non l'ID di un articolo inserito.