I’am using Generic Collection List but not working
public class Product
{
[Key]
public int p_id { get; set; }
public string p_name { get; set; }
public double p_price { get; set; }
public List<string> p_image { get; set; }
public int cat_id { get; set; }
public Category category { get; set; }
}
Solve This How to add Multiple Images in ASP.Net Core MVC CFA(code first approach)
public class Product
{
[Key]
public int p_id { get; set; }
public string p_name { get; set; }
public double p_price { get; set; }
public List<string> p_image { get; set; }
public int cat_id { get; set; }
public Category category { get; set; }
}
1
I am Supposing that List<string> p_image
contains the images paths :
Create a class (ex : ProductImage
) with property string Path {get;set;}
inside it (and do not forget the primary key),
then replace List<string> p_image { get; set; }
with List<ProductImage> p_image { get; set; }
because, when using an object, the EF core will tell the DB to create a table that have 3 columns, the Id
(image’s id), the Path
, and ProductId
(Foreign key to the Products
table, created by convention), so it can create a 1-to-M
relationship,
but when you use just a string
, it will not work, because you do not have the Foreign Key, so no 1-to-M
relationship is possible, it will work only if you have single image (1-to-1
relationship) so the path at this case is a column at the Product’s table, not at a independent table
and read the docs for better understanding
- Bonus : the naming convention on C# is Pascal case for public props, and mostly there is no need for additional context (p_ or cat_)
The result should be like this :
public class Product
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
// Replace List<string> with List<ProductImage>
public List<ProductImage> Images { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
public class ProductImage
{
[Key]
public int Id { get; set; }
public string Path { get; set; }
// Foreign Key to Product
public int ProductId { get; set; }
public Product Product { get; set; }
}
2