0

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
  • What you mean the add the multiple images? Do you mean you want to upload multiple images as bytes to the database by using the EF code first? Commented Sep 9, 2024 at 10:22

1 Answer 1

0

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; }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Can you provide the code
I added the code, I hope it is useful, + you can easily get it from chatgpt (as I did) if you send your quesion with my answer to it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.