I have a order model that has a list of products as an attribute and I want to display the orders with the products but when I try to select the items from database this exception pops
Microsoft.Data.SqlClient.SqlException: 'Invalid column name 'OrdProdOrderId'.
Invalid column name 'OrdProdProductId'.'
Here is my order model
public class Order
{
public int id { get; set; }
public int id_agent { get; set; }
[Required]
[RegularExpression("[a-zA-Z\\s]{5,}")]
public string destinator { get; set; }
[DataType(DataType.Date), Required]
public DateTime deliver_date { get; set; }
[Required]
[RegularExpression("[0-9.]+")]
public float cost { get; set; }
[NotMapped]
public List<Product> products { get; set; }
[NotMapped]
public List<bool> selected { get; set; }
}
}
The OrdProd model that is used to save witch products are in each order
public class OrdProd
{
public int OrderId { get; set; }
public int ProductId { get; set; }
public Order order { get; set; }
public List<Product> products { get; set; }
}
And this is the Action with trouble
public IActionResult Index()
{
var orders = _context.Orders;
var ord_prod_db = _context.OrdProd.ToList();
List<OrdProd> items = new List<OrdProd>();
if(orders == null || ord_prod_db == null)
{
return View();
}
List<int> uniqe = new List<int>();
var list = orders.ToList();
foreach(var item in list)
{
if (!uniqe.Contains(item.id))
{
uniqe.Add(item.id);
}
}
foreach(int id in uniqe)
{
OrdProd ord_prod = new OrdProd();
List<OrdProd> ord_pord_from_db = new List<OrdProd>();
List<Product> products_to_add = new List<Product>();
ord_pord_from_db = _context.OrdProd.Where(e => e.OrderId == id).ToList();
foreach(var item in ord_pord_from_db)
{
int i = item.ProductId; // this works fine, its returns 1 witch is the ID for the first product in the order
-----error----
var aux = _context.Products.Where(e => e.id == item.ProductId).FirstOrDefault(); - ----error----
products_to_add.Add(_context.Products.Where(e => e.id == item.ProductId).FirstOrDefault());
}
ord_prod.OrderId = id;
ord_prod.products = products_to_add;
ord_prod.order = _context.Orders.Where(e => e.id == id).FirstOrDefault();
items.Add(ord_prod);
}
return View(items);
}
}
In order prod my key is composite from OrderId and ProductId
I think it is because you have strange OrdProd class. It should be
public class OrdProd
{
public int OrderId { get; set; }
public int ProductId { get; set; }
public Order order { get; set; }
public Product product { get; set; }
}
Why you don't try this code
var productId = item.ProductId; // this works fine, its returns 1 witch is the ID for the first product in the order
var aux = _context.Products.Where(e => e.id == productId).FirstOrDefault();
products_to_add.Add(aux);